Bitwise Leftshift (<<) strange behavior

后端 未结 6 931
鱼传尺愫
鱼传尺愫 2021-01-15 13:41

gcc bitwise Leftshift (<<) strange behavior. Here is my code:

#include 
#include 

void foo(in         


        
6条回答
  •  Happy的楠姐
    2021-01-15 14:01

    Since you're shifting 32-bit ints, shifting by 32 bits would result in a zero value. However, the bitshift operation of the CPU can only shift by 0 to 31 bits as anything else is generally not useful and would only complicate the computation.

    The reason that the first example, 1<<32, seems to work, is that the compiler optimises this to 0 at compile time, while also printing a warning. The other example, 1<<(32-n), however, has a shift value that cannot be determined at compile time (thus no warning either). Instead, the CPU uses the result of the subtraction 32 - n == 32 for its shift operation, but the CPU only takes the five lowest bits and thus overflows to 0, and the result is 1 << 0 == 1.

    To work around this, you will have to either special-case n == 0, use a wider data type, or simply use fewer bits.

提交回复
热议问题