I tried to do -1 >> 1
in java, but the result printed was still -1
At the beginning, I thought this is because of sign extending nature of arithmetic right shift. But through additional tests, I found that -1 >> [0, 64]
is -1
. Why is this happening?
Asked
Active
Viewed 80 times
2

Kelvin Zhang
- 942
- 1
- 7
- 24
-
2It _is_ the sign extending nature of arithmetic right shift. `-1` is `0xffffffff`; the leftmost bit is a `1`, so when you arithmetic right shift you get more 1 bits coming in, so it stays `0xffffffff`. – Louis Wasserman Sep 22 '16 at 22:53
-
@AdrianColomitchi Not a dup of that question. In that case the answer has to do with the fact the shift operator uses only the bottom 5 bits of the shift amount, so `1>>32` is the same as `1>>0`. This question is about sign extension. I'm sure it's a dup, just not of that question. – Jim Garrison Sep 22 '16 at 22:58
1 Answers
4
This is because of sign extension. -1
is represented by the bit sequence containing only 1s. Using the right shift with sign extension therefore always yields the sequence with all bits 1, i.e. -1
, regardless of the second operand of the bitshift.

fabian
- 80,457
- 12
- 86
- 114
-
@KelvinZhang There is no sign bit. If the highest order bit is set, then this means `2^31` is subtracted from the (unsigned) number represented by the other bits. (2's- complement representation) – fabian Sep 23 '16 at 15:07