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

StackOverflow https://stackoverflow.com/questions/21894503

  •  13-10-2022
  •  | 
  •  

Question

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

Was it helpful?

Solution

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]

OTHER TIPS

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]

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.

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;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top