Search code examples
c++bit-shift

Why doesn't left bit-shift, "<<", for 32-bit integers work as expected when used more than 32 times?


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.


Solution

  • 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