Bit shifting an int 32 times in C

北城以北 提交于 2019-11-29 08:08:45
sourcejedi

It's undefined behavior

Why doesn't left bit-shift, "<<", for 32-bit integers work as expected when used more than 32 times?

which means you should avoid it like the plague. Here's some links including "What every C programmer should know about undefined behavior": http://lwn.net/Articles/511767/

Shifting by the number of bits of the operands has undefined behavior, which is why you're getting "unexpected" results.

Here is a quote about this from the C99 standard:

6.5.7 Bitwise Shift Operators [...]

3 [...] If the value of the right operand is negative or is greater than or equal to the width of the promoted left operand, the behavior is undefined.

With credit to the original source.

You are not allowed to shift a value more than it's width. How much is the with of an int number ? Well, in a 32-bit system it's 32 bit. If you try to shift an int with more than 32 in gcc, you get this warning :

warning: right shift count >= width of type [enabled by default]

If you want to get 0xFFFFFFFF you have to shift if 31 times, not 32 times. Think about it !

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