当我编写以下程序并使用 GNU C++ 编译器时,输出是 1
我认为这是由于编译器执行的旋转操作。
#include <iostream>
int main()
{
int a = 1;
std::cout << (a << 32) << std::endl;
return 0;
}
但是从逻辑上讲,如果位宽溢出就会丢失,那么输出应该是0。这是怎么回事?
代码在ideone上,http://ideone.com/VPTwj .
最佳答案
这是由于 C 中未定义的行为以及为 IA-32 处理器生成的代码在移位计数上应用了 5 位掩码这一事实共同造成的。这意味着在 IA-32 处理器上,移位计数的范围仅为 0-31。 <支持> 1
来自C 编程语言 2
The result is undefined if the right operand is negative, or greater than or equal to the number of bits in the left expression’s type.
来自IA-32 英特尔架构软件开发人员手册 3
The 8086 does not mask the shift count. However, all other IA-32 processors (starting with the Intel 286 processor) do mask the shift count to 5 bits, resulting in a maximum count of 31. This masking is done in all operating modes (including the virtual-8086 mode) to reduce the maximum execution time of the instructions.
1 http://codeyarns.com/2004/12/20/c-shift-operator-mayhem/
2 A7.8 移位运算符,附录 A. 引用手册,C 编程语言
3 SAL/SAR/SHL/SHR – Shift,第 4 章指令集引用,IA-32 英特尔架构软件开发人员手册
关于c++ - 为什么 32 位整数的左位移 "<<"在使用超过 32 次时不能按预期工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7401888/