szupie
szupie

Reputation: 856

Negative logical shift

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.

Upvotes: 2

Views: 4771

Answers (2)

newacct
newacct

Reputation: 122439

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

Upvotes: 6

polygenelubricants
polygenelubricants

Reputation: 383746

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

Upvotes: 1

Related Questions