Search code examples
cbit-shiftunsigned

bit shifting with unsigned long type produces wrong results


I'm a bit confused because I wanted to initialize a variable of type unsigned long whose size is 8 bytes on my system (on every modern system I suppose). When I want to assign 1 << 63 to the variable, I get a compiler warning however and the number is in fact 0. When I do 1 << 30 I get the expected result of 2 ^ 30 = 1073741824. Yet when I do 1 << 31, I get the result of 2 ^ 64 (I think; actually this shouldn't be possible) which prints 18446744071562067968.

Can anyone explain this behaviour to me?


Solution

  • 1 << 63 will be computed in int arithmetic, and your int is probably 32 bit.

    Remedy this by promoting the left argument: 1ULL << 63 will do it.

    ULL means the expression will be at least 64 bits.