4

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.

2 Answers 2

9

<< (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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you very much... I think I am getting it.
The reason for only considering the lower bits is that the hardware does it that way. It would be inefficient to do it differently (say shift left for positive and right for negative numbers, or return 0 if you shift an int left by more than 31).
@axtavt you said that it is only the 5 LSB's that gets included in the operation for int. So instead of this whole thing 1111111111111111111111111110110, only 10110 gets into the spotlight. My problem is that the bits are in 2's complement but then when you take only the five bits according to the convention, you consider it in simple binary representation instead of 2's complement. Why?
5

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 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.