Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't the bit-shift of a variable and a number have the same result?

Tags:

c++

bit-shift

I'm shifting some bits and just realized that doing the operation using a variable doesn't have the same result as using a number. See the example below.

int a = 97;
int b = 0;

b = 1 << a;
printf("%d\n", b); 
// 2

b = 1 << 97;
printf("%d\n", b); 
// 0 - warning: shift count >= width of type [-Wshift-count-overflow]

like image 964
D. Leonardo Avatar asked Nov 21 '25 10:11

D. Leonardo


1 Answers

Since the result of a left shift with a right operand larger than the length in bits of the left operand is undefined, any result is possible from the expression.

In the variable case (1 << a), since a is 97 (larger than the number of bits in an int), the most likely results are 1 << (97 % 32) == 1 << 1 == 2 or 0, typically depending on how the hardware (CPU) handles these shifts.

With a constant (1 << 97), the compiler knows you're shifting too far, issues the warning (which is not required), and defines the result as 0 (also not required).

like image 167
1201ProgramAlarm Avatar answered Nov 24 '25 00:11

1201ProgramAlarm