1

I currently have a strange feature in java, I'm attempting to circumvent.If I define a byte as 0x80 and I shift right 1 position, java will output 0xC0, not 0x40. Does anyone know why this is?

Also if I input 0x70, and shift right 1 position, it'll correctly output 0x38.

I've noticed this behavior in shorts and ints also. When ever the MSB is set, the MSB will stay set irregardless, and when that value will be cast to a larger value (ala int) the 'new' spaces will be filled with set bits.

Basically what I'm asking is this behavior correct?

Valarauca
  • 1,041
  • 3
  • 10
  • 23

1 Answers1

6

Basically what I'm asking is this behavior correct?

Yes, it is correct. Even though you haven't shown your code, it is clear that you are using >> for right shift, where you expect the behavior of the >>> operator. The former does sign extension to preserve the usually wanted effect of division by powers of two for negative numbers. The latter is a pure bitfield right-shift operator.

Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436