对于32位整数,为什么不使用左移位位移,“<”和“32位整数工作正常,超过32次? [英] Why doesn't left bit-shift, "<<", for 32-bit integers work as expected when used more than 32 times?

查看:405
本文介绍了对于32位整数,为什么不使用左移位位移,“<”和“32位整数工作正常,超过32次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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


如果右操作数为负数,或大于或等于左表达式类型中的位数,则未定义。


em> IA-32英特尔架构软件开发人员手册 3


8086不会屏蔽移位计数。但是,所有其他IA-32处理器(从Intel 286处理器开始)会将移位计数屏蔽为5位,导致最大计数为31.这种屏蔽在所有操作模式(包括虚拟8086模式)下完成,减少指令的最长执行时间。








//codeyarns.com/2004/12/20/c-shift-operator-mayhem/



2 A7.8 Shift操作符,附录A参考手册,C编程语言



3 SAL / SAR / SHL / SHR - 设置参考,IA-32英特尔体系结构软件开发人员手册


When I write the following program and use the GNU C++ compiler, the output is 1 which I think is due to the rotation operation performed by the compiler.

#include <iostream>

int main()
{
    int a = 1;
    std::cout << (a << 32) << std::endl;

    return 0;
}

But logically, as it's said that the bits are lost if they overflow the bit width, the output should be 0. What is happening?

The code is on ideone, http://ideone.com/VPTwj.

解决方案

This is caused due to a combination of an undefined behaviour in C and the fact that code generated for IA-32 processors has a 5 bit mask applied on the shift count. This means that on IA-32 processors, the range of a shift count is 0-31 only. 1

From The C programming language 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.

From IA-32 Intel Architecture Software Developer’s Manual 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 Shift Operators, Appendix A. Reference Manual, The C Programming Language

3 SAL/SAR/SHL/SHR – Shift, Chapter 4. Instruction Set Reference, IA-32 Intel Architecture Software Developer’s Manual

这篇关于对于32位整数,为什么不使用左移位位移,“&lt;”和“32位整数工作正常,超过32次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆