无法在 C 中打印长整数

Impossible to print a long long integer in C

我知道有很多关于这个主题的主题,但其中 none 帮助我解决了我的问题。 我在 Code::Blocks 上工作(在 "Properties>Project Build Options>Compiler Settings>Other Options" 中使用选项 -std=c99),但以下代码没有给出预期的输出:

long long val=1<<33;
printf("value: %llu",val);

实际上我在终端中获得了"value: 0"。 我该如何解决这个问题?

当我写 30 而不是 33(所以 val 是一个整数)时,我得到了正确的答案。我也试过 %lld 但这没有帮助。

1<<33 将为 32 位 int.

调用未定义的行为

C11:6.5.7 移位运算符:

The result of E1 << E2 is E1 left-shifted E2 bit positions; vacated bits are filled with zeros. If E1 has an unsigned type, the value of the result is E1 × 2E2, reduced modulo one more than the maximum value representable in the result type. If E1 has a signed type and nonnegative value, and E1 × 2E2 is representable in the result type, then that is the resulting value; otherwise, the behavior is undefined.

由于您没有以任何方式限定文字 1 和 33,因此 1<<33 将具有 int 作为其类型。如果 int 是 32 位(在针对 64 位的编译器上很常见)那么这个表达式将产生 未定义的行为.

一个简单的解决方法是写 1LL << 331LLlong long,33 也将被提升为该类型。 C++ 标准保证 long long 至少是 64 位。

尽管我更喜欢 static_cast<std::int64_t>(1) << 33

在很多方面

移位 1<<33 未在 long long 类型上完成。 1 在这里是一个 int;将其转换为 long long 或使用 LL 作为后缀,例如 1LL << 33.