问题描述
我在 C 中有此代码(仅供学习):
I have this code in C (it's for study only):
char x;
uint64_t total = 0;
for(x = 20; x < 30; x++){
total = (((((1 << x) * x) / 64) + 1) * sizeof(uint64_t));
printf("%d - %llu
", x, total);
}
打印的内容:
20 - 2621448
21 - 5505032
22 - 11534344
23 - 24117256
24 - 50331656
25 - 104857608
26 - 218103816
27 - 18446744073625665544
28 - 18446744073575333896
29 - 18446744073508225032
为什么在 x > 26 我有那些奇怪的值?我在 Ubuntu 10.10 64 位上使用 gcc 4.6.1.
Why at x > 26 do I have those strange values? I'm at gcc 4.6.1 on Ubuntu 10.10 64 bits.
推荐答案
因为 1
是一个 int
,32 位,所以 (1 <<27)*27
溢出.使用 1ull
.
Because 1
is an int
, 32 bits, so (1 << 27)*27
overflows. Use 1ull
.
关于您的评论,如果 x
是 uint64_t
,则 1 << 仍然是一个
int
,但是对于乘法,它会被转换为 uint64_t
,所以不会有溢出.然而,如果 x >= 31
,1 << 将是未定义的行为(因为结果值不能用有符号的 32 位整数类型表示).
Regarding your comment, if
x
is a uint64_t
, then 1 << x
is still an int
, but for the multiplication it would be cast to uint64_t
, so there'd be no overflow. However, if x >= 31
, 1 << x
would be undefined behaviour (as the resulting value cannot be represented by a signed 32 bit integer type).
这篇关于C 64 位左移失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!