Question

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?
Was it helpful?

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.

OTHER TIPS

As far as I know the meaning of >> and >>> has always been the same in Java.

Why make this change?

Machine independence. The meaning of >> is somewhat implementation dependent in C.

Signed left shift and unsigned left shift are exactly equivalent, so there's no need to have a separate operator.

On the other hand, Java has no unsigned types, so it can't depend on the type to figure out what shift to use.

For reference, I think you have it backwards -- >> is signed right shift, >>> is unsigned right shift.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top