gpt4 book ai didi

c - 如何正确地将两个 long long int 相乘?

转载 作者:太空宇宙 更新时间:2023-11-04 05:21:50 25 4
gpt4 key购买 nike

我想将以 2^32 为基础的长数相乘。我已经想到了一个很好的算法来做到这一点,但不幸的是我被困住了。我遇到的情况是如何将两个长整数相乘并在 2^32 的基础上表示它。

#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
typedef unsigned int uint32;
typedef unsigned long long uint64;
int main(int argc, char* argv[] )
{

uint64 a = (uint64)ULONG_MAX;
printf("%llu\n", a);
uint64 b = (uint64)ULONG_MAX;
printf("%llu\n", b);
uint64 c = (uint64)(a*b);

printf("%llu\n", c); // prints 1. that would be to lower 32 bits of the results. the upper half is 0xFFFFFFFE

printf("%llu\n", ULLONG_MAX);
system("pause");
}

为什么 ULLONG_MAX 与 ULONG_MAX 相同?根据http://en.wikipedia.org/wiki/Limits.h#Member_constants应该是 18,446,744,073,709,551,615 我

正如您从我的评论中看到的那样,我想要两个 uint32 中的乘法结果。下半部分为 0x1,上半部分为 0xFFFFFFFE。我如何获得这些值?

(我在 SO 上发现了这个问题,但这对我的情况没有帮助,因为给出的答案与我的想法相似:Multiplying two long long ints C)

编辑:我的系统是 Windows XP 32 位。我正在使用 gcc 3.4.2 (mingw-special)

我在运行代码时得到的输出:

4294967295
4294967295
1
4294967295

编辑2:

  printf("%i\n", sizeof(unsigned long));
printf("%i\n", sizeof(unsigned long long));

返回

4
8

编辑 3:感谢 Petesh,我找到了解决方案:

  printf("%lu\n", c & 0xFFFFFFFF);
printf("%lu\n", (c >> 32));

最佳答案

提示在系统中(“暂停”)——你在 Windows 上?使用 Microsoft visual c 运行时打印 long long 需要使用“%I64u”(这是一个大写的 i)。

这是基于 SO 问题 How do you printf an unsigned long long int(the format specifier for unsigned long long int)?

关于c - 如何正确地将两个 long long int 相乘?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3542160/

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