byte b = -1; // b = -1 1111_1111 b <<= 1; // b = -2 1111_1110 b >>>= 1; // b = -1 1111_1111 

In comments - the value of b in debug. The last line, b, should be 0111_1111, because an unsigned right shift was applied. Where is the mistake?

    1 answer 1

    "Error" in the Java specification. All operations with integers are performed with 32-bit precision, and their result is an int (except when one of the operands is long ).

    Code

     b >>>= 1; 

    is equivalent to

     b = (byte)( b >>> 1 ); 

    The shift operator performs unary numeric promotion for each argument, casting their types to int (or long ). The byte extension to int preserves the value, i.e. (byte)-2 becomes (int)-2 , hence the unit to the left as a result of the shift.

    To obtain the desired result, you can write this:

     b = (byte)((b & 0xFF) >>> 1);