Explicit conversion from int to byte in Java

后端 未结 4 691
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-20 08:50

I am trying to convert an int to byte.

int i = 128;
byte b = (byte) i;

I know the range of byte if -128 to 127 and the rule of storing an i

4条回答
  •  佛祖请我去吃肉
    2020-12-20 09:12

    Casting to byte doesn't mean int_value % byte_range. It means that only the last 8 significant bits are kept in the byte value. At first that seems to mean the same thing, but bytes are signed.

    The int value 128 is the following bits:

    00000000 00000000 00000000 10000000
    

    When the last 8 bits are kept, this is the result:

    10000000
    

    Now, the most significant bit in the byte is interpreted as -128, not +128 as it was in the int.

    The value 128 overflows a byte, and the result is negative because of that most significant bit being set.

提交回复
热议问题