Left shift an integer by 32 bits

前端 未结 2 600
悲哀的现实
悲哀的现实 2020-12-06 15:17

Under GCC, the following code always return the left operand of << if num1s == 0:

0xFFFFFFFFu << (32-num1s);

2条回答
  •  既然无缘
    2020-12-06 15:42

    CoryKramer has answered why it is an undefined behavior by standard.

    I'll try to expain how it works in the real situation. C++ compilers usually implement << and >> operators for 32-bit integers as assembler instructions without checking the operand range. It means that the result depends on the processor-specific implementation of the shift instructions.

    For example, Intel processor specification for 32-bit SHL/SHR/SAL/SAL instructions says:

    The destination operand can be a register or a memory location. The count operand can be an immediate value or register CL. The count is masked to five bits, which limits the count range to 0 to 31.

    It means that a << b becomes a << (b & 0x1f) on Intel processors. So shifting by 32 bits means no shift.

    But you should not rely on this information! The compiler can also optimize the code and implement the shift operator using vector instructions. In this case, the behavior is unspecified even by processor specifications.

提交回复
热议问题