Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

bit-shift

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

like image 795
krb686 Avatar asked Dec 06 '25 02:12

krb686


1 Answers

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]

like image 114
Shafik Yaghmour Avatar answered Dec 08 '25 17:12

Shafik Yaghmour



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!