问题
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.
回答1:
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://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.19
回答2:
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
- JLS 15.9 Shift Operators
- "If the promoted type of the left-hand operand is
int
(long
), only the five (six) lowest-order bits of the right-hand operand are used as the shift distance."
- "If the promoted type of the left-hand operand is
- Java Puzzlers: Puzzle 27: Shifty
i
's - What’s the reason high-level languages like C#/Java mask the bit shift count operand?
来源:https://stackoverflow.com/questions/2671718/negative-logical-shift