Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
381 views
Welcome To Ask or Share your Answers For Others

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...