gpt4 book ai didi

c - 为什么我需要从 1 << 64 中减去二得到 2^64 - 1?

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

此程序输出的每一行都等于 2 ^ i - 2,除了最后一行,它等于 2 ^ 64 - 1。这是为什么?

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

int main(void) {
unsigned long long ONE = 1;
unsigned long long i;
for (i = 1; i <= 64; i++) {
printf("%"PRIu64"\n", (ONE << i) - 2);
}

return EXIT_SUCCESS;
}

输出:

0
2
6
14
30
62
126
254
510
1022
2046
...
4611686018427387902
9223372036854775806
18446744073709551615

最佳答案

您将 64 位转换为 64 位类型(unsigned long long 在您的机器上),这是未定义的行为。

顺便说一句,unsigned long long ONE = 1; 是糟糕的编码风格,您可以简单地使用 1ULL

C11 §6.5.7 Bitwise shift operators

The integer promotions are performed on each of the operands. The type of the result isthat of the promoted left operand. If the value of the right operand is negative or is greater than or equal to the width of the promoted left operand, the behavior is undefined.

关于c - 为什么我需要从 1 << 64 中减去二得到 2^64 - 1?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18523392/

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