gpt4 book ai didi

c - 两个 32 位数字相乘...这段代码有什么问题

转载 作者:行者123 更新时间:2023-11-30 15:56:10 39 4
gpt4 key购买 nike

我正在尝试将两个 32 位数字 a 和 b 相乘,这应该给出 64 位结果。由于 a 和 b 是无符号 32 位整数,我想出了这个:

r = a * b

r = ((ah << 16) + al) * ((bh << 16) + bl)
= ((ah * 2^16) + al) * ((bh * 2^16) + bl)
= (ah * 2^16) * (bh * 2^16) + (ah * 2^16) * bl + al * (bh * 2^16) + al * bl
= (ah * bh * 2^32) + (ah * bl * 2^16) + (al * bh * 2^16) + (al * bl)
= ((ah * bh) << 32) + ((ah * bl) << 16) + ((al * bh) << 16) + (al * bl)
= ((ah * bh) << 32) + ((ah * bl + al * bh) << 16) + (al * bl)

然后我将其翻译成c,如下

static void _mul64(unsigned int a, unsigned int b, unsigned int *hi, unsigned int *lo) {
unsigned int ah = (a >> 16), al = a & 0xffff,
bh = (b >> 16), bl = b & 0xffff,
rh = (ah * bh), rl = (al * bl),

rm1 = ah * bl, rm2 = al * bh,
rm1h = rm1 >> 16, rm2h = rm2 >> 16,
rm1l = rm1 & 0xffff, rm2l = rm2 & 0xffff,
rmh = rm1h + rm2h, rml = rm1l + rm2l;

rl = rl + (rml << 16);
rh = rh + rmh;
if(rml & 0xffff0000)
rh = rh + 1;
*lo = rl;
*hi = rh;
}
然而,当我运行这个小测试时,将 a = 0xFFFFFFFF 与 b = 0xFFFFFFFF 相乘,并应产生 0xFFFFFFFE00000001,我得到的是 0xFFFFFFFD00000001。我做错了吗?

int main(int argc, char **argv) {
unsigned int a, b, rl, rh;
unsigned long long r;
unsigned long long r1, r2, r3;

a = 0xffffffff;
b = 0xffffffff;
mul64(a, b, &rh, &rl);
r1 = ((unsigned long long) rh << 32) + rl;
r2 = (unsigned long long) a * b;

_mul64(a, b, &rh, &rl);
r3 = ((unsigned long long) rh << 32) + rl;
printf("a = 0x%08x, b = 0x%08x\n", (unsigned) a, (unsigned) b);
printf("_mul64: 0x%16llx\n", (unsigned long long) r3);
printf("a * b = 0x%16llx\n", (unsigned long long) r2);
return 0;
}

最佳答案

您要在此处添加 16 位数量

rm1l = rm1 & 0xffff,    rm2l = rm2 & 0xffff,
rmh = rm1h + rm2h, rml = rm1l + rm2l;

并将rml左移16位添加到rl

rl = rl + (rml << 16);

当两个 16 位量之和变成 17 位量时,丢弃进位。

此外,后一个总和可能会超过 32 位范围,在这种情况下,您会丢失另一个进位位。

关于c - 两个 32 位数字相乘...这段代码有什么问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11438384/

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