gpt4 book ai didi

c++ - Visual C++ x64 带进位加法

转载 作者:可可西里 更新时间:2023-11-01 18:19:07 30 4
gpt4 key购买 nike

由于 ADC 似乎没有内在函数,而且我不能在 Visual C++ 中使用 x64 体系结构的内联汇编程序,如果我想编写一个使用 add with carry 的函数,但将其包含在一个C++ 命名空间?

(不能选择使用比较运算符进行仿真。这个 256 兆比特的加法对性能至关重要。)

最佳答案

There is now an instrinsic对于 MSVC 中的 ADC:_addcarry_u64。以下代码

#include <inttypes.h>
#include <intrin.h>
#include <stdio.h>

typedef struct {
uint64_t x1;
uint64_t x2;
uint64_t x3;
uint64_t x4;
} uint256;

void add256(uint256 *x, uint256 *y) {
unsigned char c = 0;
c = _addcarry_u64(c, x->x1, y->x1, &x->x1);
c = _addcarry_u64(c, x->x2, y->x2, &x->x2);
c = _addcarry_u64(c, x->x3, y->x3, &x->x3);
_addcarry_u64(c, x->x4, y->x4, &x->x4);
}

int main() {
//uint64_t x1, x2, x3, x4;
//uint64_t y1, y2, y3, y4;
uint256 x, y;
x.x1 = x.x2 = x.x3 = -1; x.x4 = 0;
y.x1 = 2; y.x2 = y.x3 = y.x4 = 0;

printf(" %016" PRIx64 "%016" PRIx64 "%016" PRIx64 "%016" PRIx64 "\n", x.x4, x.x3, x.x2, x.x1);
printf("+");
printf("%016" PRIx64 "%016" PRIx64 "%016" PRIx64 "%016" PRIx64 "\n", y.x4, y.x3, y.x2, y.x1);
add256(&x, &y);
printf("=");
printf("%016" PRIx64 "%016" PRIx64 "%016" PRIx64 "%016" PRIx64 "\n", x.x4, x.x3, x.x2, x.x1);
}

从 Visual Studio Express 2013 生成以下程序集输出

mov rdx, QWORD PTR x$[rsp]
mov r8, QWORD PTR x$[rsp+8]
mov r9, QWORD PTR x$[rsp+16]
mov rax, QWORD PTR x$[rsp+24]
add rdx, QWORD PTR y$[rsp]
adc r8, QWORD PTR y$[rsp+8]
adc r9, QWORD PTR y$[rsp+16]
adc rax, QWORD PTR y$[rsp+24]

如预期的那样,它有一个 add 和三个 adc

编辑:

对于 _addcarry_u64 的作用似乎有些混淆。如果您查看我在此答案开头链接到的 Microsoft 文档,它表明它不需要任何特殊硬件。这会生成 adc 并且它将在所有 x86-64 处理器上运行(并且 _addcarry_u32 甚至可以在更旧的处理器上运行)。它在我测试过的 Ivy Bridge 系统上运行良好。

但是,_addcarryx_u64 确实需要 adx(如 MSFT 的文档所示),而且它确实无法在我的 Ivy Bridge 系统上运行。

关于c++ - Visual C++ x64 带进位加法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9145644/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com