问题
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?
回答1:
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.
回答2:
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.
回答3:
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.
来源:https://stackoverflow.com/questions/9722941/shift-operation-implementation-in-java