简体   繁体   English

按位移位1 << 45怎么得到大整数

[英]How come I get a big int when I bitwise shift 1 << 45

Why do I get such a big int? 为什么我会有这么大的整数?

int ans = 1 << 45;
printf("Check: %d", ans);
return 0;

Check: 1858443624 支票:1858443624

This is undefined behavior in C. Anything can happen, including stuff like processor exceptions, or unpredictable changes in other parts of the program (which can happen as a side effect of aggressive compiler optimizations). 这是C语言中未定义的行为。任何事情都可能发生,包括诸如处理器异常之类的东西,或者程序其他部分的不可预测的变化(这可能是积极的编译器优化的副作用)。

6.5.7/3 [...] 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. 6.5.7 / 3 [...]如果右操作数的值为负或大于或等于提升后的左操作数的宽度,则行为不确定。

Source 资源

According to the C standard 根据C标准

An expression is shifted by a negative number or by an amount greater than or equal to the width of the promoted expression (6.5.7). 表达式移位负数或大于或等于提升的表达式的宽度(6.5.7)的量。

is undefined behavior, so the compiler is free to do anything for the code you give here. 是未定义的行为,因此编译器可以为您在此处提供的代码自由地做任何事情。

90? 90? No way. 没门。 You need to read what bit-shifting does. 您需要阅读移位的功能。 1<<45 is essentially 2^45 . 1<<45本质上是2^45 Besides, int is only 31 bits (excluding the sign bit), so by trying to shift 45 bits, you're causing undefined behavior. 此外, int只有31位(不包括符号位),因此,尝试将45位移位会导致未定义的行为。

Quick example: 快速示例:

1 << 0  =  1  = 0x01  = 00000001b
1 << 1  =  2  = 0x02  = 00000010b
1 << 2  =  4  = 0x04  = 00000100b
1 << 3  =  8  = 0x08  = 00001000b

clang (as used in X-Code; AFAIK they don't use gcc anymore) is funny with this: clang(用于X代码; AFAIK他们不再使用gcc)对此很有趣:

stieber@gatekeeper:~$ clang Test.c -Wno-shift-count-overflow; ./a.out
Check: -1344872728
stieber@gatekeeper:~$ clang Test.c -Wno-shift-count-overflow; ./a.out
Check: -1066238232
stieber@gatekeeper:~$ clang Test.c -Wno-shift-count-overflow; ./a.out
Check: -1373126936
stieber@gatekeeper:~$ clang Test.c -Wno-shift-count-overflow; ./a.out
Check: 779153128

Apparently, they randomize the result :-) 显然,他们将结果随机化:-)

1) As everybody has already said, the answer is "undefined behavior". 1)正如大家已经说过的,答案是“不确定的行为”。

2) In practice, just about every compiler I'm familiar with will give you "0". 2)实际上,几乎我熟悉的每个编译器都会为您提供“ 0”。

3) In practice, most self-respecting compilers will also give you a warning: 3)实际上,大多数自重的编译器也会给您警告:

x.cpp: In function `int main (int, char **)':
x.cpp:7: warning: left shift count >= width of type

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM