views:

180

answers:

2

In Java, why does -32 >>> -1 = 1 ?
It's not specific to just -32. It works for all negative numbers as long as they're not too big.
I've found that
x >>> -1 = 1
x >>> -2 = 3
x >>> -3 = 7
x >>> -4 = 15
given 0 > x > some large negative number

Isn't >>> -1 the same as << 1? But -32 << 1 = -64.
I've read up on two's complements, but still don't understand the reasoning.

+4  A: 

It's because when you are shifting a 32-bit int, it just takes the last 5 bits of the shift distance. (i.e. mod 32), so -1 mod 32 = 31, so you are shifting right by 31 bits. When you are shifting a negative number (the beginning bits of which are all 1s), you end up with a 1. Similarly, shifting right by -2 is shifting right by 30 bits, etc. If you shift a long, it would take 6 bits of the shift distance. See here for the specification of how the shift operators work: http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.19

newacct
As to why, presumably because different processors have different rules. For instance, IIRC ARM will take the bottom (unsigned) byte for the shift size. This rule makes it reasonably efficient on any reasonable processor (and ARM).
Tom Hawtin - tackline
I see now. I had previously read that Java ints shifts on a multiple of 32 positions (x<<32 = x, x<<33 = x<<1), and also that negative ints are filled with 1's up to 32 bits. However, I never put the two together. I didn't realize that -1 is 31, which leaves only the beginning bit remaining.Thanks for clarifying this.
szupie
A: 

Java masks the right operand based on the size of the left operand.

For a 32-bit int i,

i << N   --> i << (N mod 32)

For a 64-bit long num,

num << N --> num << (N mod 64)

This masking of the shift count operand also applies to >> and >>>.

See also

polygenelubricants