Weird result after assigning 2^31 to a signed and unsigned 32-bit integer variable

非 Y 不嫁゛ 提交于 2019-11-28 13:46:44

On this line:

unsigned long long n = 1<<32;

The problem is that the literal 1 is of type int - which is probably only 32 bits. Therefore the shift will push it out of bounds.

Just because you're storing into a larger datatype doesn't mean that everything in the expression is done at that larger size.

So to correct it, you need to either cast it up or make it an unsigned long long literal:

unsigned long long n = (unsigned long long)1 << 32;
unsigned long long n = 1ULL << 32;

The reason 1 << 32 fails is because 1 doesn't have the right type (it is int). The compiler doesn't do any converting magic before the assignment itself actually happens, so 1 << 32 gets evaluated using int arithmic, giving a warning about an overflow.

Try using 1LL or 1ULL instead which respectively have the long long and unsigned long long type.

The line

unsigned long long n = 1<<32;

results in an overflow, because the literal 1 is of type int, so 1 << 32 is also an int, which is 32 bits in most cases.

The line

unsigned long long n = 1<<31;

also overflows, for the same reason. Note that 1 is of type signed int, so it really only has 31 bits for the value and 1 bit for the sign. So when you shift 1 << 31, it overflows the value bits, resulting in -2147483648, which is then converted to an unsigned long long, which is 18446744071562067968. You can verify this in the debugger, if you inspect the variables and convert them.

So use

unsigned long long n = 1ULL << 31;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!