Replace C >>= 1 with C >>>= 1 and the output becomes:
C = -32 (0xffffffe0) C = 2147483632 (0x7ffffff0) B = -16
So the unsigned shift behaves as advertised but on an integer primitive not a byte, so the -16 result for B is a product of a narrowing cast where the three highest bytes are lopped off the resulting integer.
Originally posted by Keith Tingle: ...where the three highest bytes are lopped off the resulting integer.
That's exactly right, Keith. There are a couple important things to take note of in your sample code. First of all, any operands of a bit shift operation are automatically promoted to ints. Therefore, if you have a byte with value -16, which has a binary equivalent of 11110000, it becomes an int with value -16, which has a binary equivalent of 11111111 11111111 11111111 11110000.
Second, keep in mind that compound assignment operators, such as +=, -=, and >>>=, all contain an implicit cast. Therefore, this code:
Is equivalent to this code:
So, what is really happening?
Well, first we promote our byte to an int and we end up with the value we saw before (11111111 11111111 11111111 11110000). Next, we shift that to the right one position and push a 0 into the highest order bit. That leaves us with 01111111 11111111 11111111 11111000. Finally, we perform a cast, which lops off the highest 3 bytes (which includes the 0 we just shifted in). That leaves us with b being assigned 11111000. That, of course, is -8.