2

I have a long which is made with this code:

long binary = 0b1L<< 63;

This gives the expected result, a one at the 63rd index:

1000000000000000000000000000000000000000000000000000000000000000

But when I take this long, and apply the >> operator to it, it gives me an unexpected result. For example, when I call this code snippet on the above binary:

long newBinary = binary >>8;

It shifts right the right amount, but it fills the leading zeros with ones:

1111111110000000000000000000000000000000000000000000000000000000

Is there a specific reason why this is happening?

1 Answers1

0

>> is the signed right shift operator, which fills the leftmost position with the sign bit (leftmost bit of the original number) each time. On the other hand, the unsigned right shift operator, >>>, always fills with 0.

Steps:

1000000000000000000000000000000000000000000000000000000000000000

Shift right 8 positions:

000000001000000000000000000000000000000000000000000000000000000

Fill shifted bits on the left with original sign bit (1):

111111111000000000000000000000000000000000000000000000000000000

See also: Bitwise and Bit Shift Operators

Unmitigated
  • 76,500
  • 11
  • 62
  • 80