Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shifting by Negative Numbers

I am pretty confused with this expression here. I am a Java programmer but I am not very well versed with bit manipulation.

I think I understand the below correctly:

Input : 1 << 10
Output: 0000000000000000000010000000000

For positive numbers, I think it is you move 1 by 10 bits.

The confusion is when I have the below:

int val = -10 (binary representation : 1111111111111111111111111110110 )
Input : 1 << val
Output: 0000000010000000000000000000000 

That would be really great if someone can explain me the meaning of left shifting or right shifting by negative number.

like image 211
dharam Avatar asked Dec 08 '22 12:12

dharam


2 Answers

<< (and other shift operators) only takes 5 least significant bits of its right operand for int, and 6 for long, because it makes no sense to shift int by more than 31.

In your case it's 0b10110 = 22.

Therefore 1 << (-10) is equivalent to 1 << 22.

like image 71
axtavt Avatar answered Jan 10 '23 22:01

axtavt


From the JLS, section 15.19:

If the promoted type of the left-hand operand is int, only the five lowest-order bits of the right-hand operand are used as the shift distance. It is as if the right-hand operand were subjected to a bitwise logical AND operator & (§15.22.1) with the mask value 0x1f (0b11111). The shift distance actually used is therefore always in the range 0 to 31, inclusive.

In other words,

1 << -10

is equivalent to:

1 << (-10 & 0x1f)

... which is

1 << 22
like image 36
Jon Skeet Avatar answered Jan 10 '23 22:01

Jon Skeet