Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 465
borchero Avatar asked Jul 31 '15 10:07

borchero


1 Answers

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

Remedy this by promoting one of the arguments: 1ULL << 63 will do it.

ULL means the expression will be at least 64 bits.

like image 194
P45 Imminent Avatar answered Oct 26 '22 23:10

P45 Imminent