Shifting a 32 bit integer by 32 bits

ⅰ亾dé卋堺 提交于 2019-11-26 23:17:47

问题


I'm slinging some C code and I need to bitshift a 32 bit int left 32 bits. When I run this code with the parameter n = 0, the shifting doesn't happen.

int x = 0xFFFFFFFF;
int y = x << (32 - n);

Why doesn't this work?


回答1:


Shift at your own peril. Per the standard, what you want to do is undefined behavior.

C99 §6.5.7

3 - The integer promotions are performed on each of the operands. The type of the result is that of the promoted left operand. 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.

In other words, if you try to shift a 32bit value by anything more than 31 bits, or a negative number, you're results are undefined.




回答2:


According to section 3.3.7 Bitwise shift operators in the draft of C89 (?) standard:

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

Assuming int is 32-bit on the system that you are compiling the code in, when n is 0, you are shifting 32 bits. According to the statement above, your code results in undefined behavior.



来源:https://stackoverflow.com/questions/18799344/shifting-a-32-bit-integer-by-32-bits

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