• Post Reply Bookmark Topic Watch Topic
  • New Topic

shift  RSS feed

 
bharath pawan
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
-5>>-2
please explain
 
Rob Spoor
Sheriff
Posts: 21095
85
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
-5 >> -2

Let's assume these are ints - it could work for longs as well but then you'll use 64 bits instead of 32.

-5 in bit notation is
1111 1111 1111 1111 1111 1111 1111 1011

Now please note that the shift will always be modulo 32 for ints and modulo 64 for longs. Therefore, -5 >> -2 is equal to -5 >> 30

So all bits are shifted 30 places to the right, filling the left with the left-most bit of the original, 1:
1111 1111 1111 1111 1111 1111 1111 1111
Of this number, which is -1, only the last two bits are taken from the original.

Now if you want to add zeros at the start, use >>> instead of >>. This will result in:
0000 0000 0000 0000 0000 0000 0000 0011
which is 3.
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, I didn't know that. Here's the relevant bit in the JLS: -

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. The shift distance actually used is therefore always in the range 0 to 31, inclusive.

If the promoted type of the left-hand operand is long, then only the six 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 0x3f. The shift distance actually used is therefore always in the range 0 to 63, inclusive.


Now, who can tell me what on Earth the point of this is?
 
Rob Spoor
Sheriff
Posts: 21095
85
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ignoring everything after the 5th / 6th bit will do the same as modulo.

I think they did this because the sizes of int and long are 32 and 64 bit respectively, and the people who invented Java didn't see any logic in shifting more than 31 / 63 (basically making your number either 0 or -1) or shifting less than 0 (shifting the other way around).
Of course the modulo is kinda weird; if I'd want to right shift an integer 33 I'd want 0 or -1, not half the number I had.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!