Search code examples
javaclanguage-implementation

Shift operation implementation in java


I recently used the shift operators in Java and noticed that the >> operator does not have the same meaning as >> in C. In Java >> is Signed shift that keeps the first bit at the same value. In Java the equivalent to C shift is the >>> operator. The left shift operator (<<) is the same as in C and just shifts ignoring the first bit.

The things I wondered are

  • Why make this change?
  • Why is the notation not consistent so >> and << are signed shift and >>> and <<< are unsigned?
  • Is there any use for a signed shift operator?

Solution

  • There is never any need for a sign-aware left shift, since 2:s complement representation stores the sign in the most significant bit.

    There's no difference between a value shifted one bit to the left in some kind of "sign-aware" manner, there's nothing you can do differently. Shift the bits to the left, insert a 0 in the least significant bit, and you're done.

    With signed numbers, shifting right is not so clear-cut, which is why there are two operators.