c++ - 为什么 32 位整数的左位移 "<<"在使用超过 32 次时不能按预期工作?

标签 c++ bit-shift

当我编写以下程序并使用 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/

相关文章:

c++ - 带有引用折叠的函数模板重载

c++ - 在顶层使用 shared_ptr 而不是 scoped_ptr 有什么优势吗?

c++ - 重命名()返回-1。如何知道重命名失败的原因?

c - 如何使用按位运算符连接 2 个数字,同时保持变量的初始值不变?

c++ - 为什么这种计算整数体系结构符号的方法是特定的

python 字节数组

c++ - 纹理不适用于我的 3d Cube directX

c++ - 如何将整数结构初始化为零?

c - 负数右移

c - C 问题 : Vacated Bits Not 0 When Shifting ~0? 中的右移无符号整数