Is there a difference between bitshift by a constant versus bitshifting by a variable with the same value, in C?

 ̄綄美尐妖づ 提交于 2019-12-24 03:35:24

问题


I'm attempting to bitshift the value 0xFFFFFFFF by 32 bits, and it correctly comes to 0 if I write

x = x << 32;

however it stays as 0xFFFFFFFF

when I write:

x = x << y

when y = 32

I really don't understand this at all.

I need to be able to use a variable though, for a function that shifts by 32 - n

Edit

If << 32 is undefined, then I really can't perceive a way to create a function that pads n - upper bits with 1's


回答1:


It is undefined behavior to shift by the bit length of a variable or greater. From the draft C99 standard section 6.5.7 Bitwise shift operators:

[...]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.

As Pascal says, you need to make a special case or use a wider type.

gcc in some cases can generate a warning for this see it live:

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




回答2:


Shifting a variable by the number of bits it contains, or more, is undefined behavior. Assuming that x is 32 bits, there is no "correct" result.

The compiler that I use identifies this programming error:

x.c:3:3: error: left shift count >= width of type [-Werror]



回答3:


There is no difference of behavior if y is of type int (because the literal 32 is also of type int) and if your program has defined behavior.

If x is of a 32 bits wide type, your program invokes undefined behavior, so everything can happen.




回答4:


You might want to do as follow:

unsigned int x;
unsigned long bx = ((unsigned long)x)&0xFFFFFFFFUL;
int n = 0; // put whatever you have
int y = 32-n;
bx = bx << y;

x = bx&0xFFFFFFFFUL;


来源:https://stackoverflow.com/questions/21894503/is-there-a-difference-between-bitshift-by-a-constant-versus-bitshifting-by-a-var

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