Explicit conversion from int to byte in Java

后端 未结 4 694
佛祖请我去吃肉
佛祖请我去吃肉 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:18

    Logic is simple, Java numbers are always signed in two's complement.

    Now a byte has 8 bits and 128 is 10000000. When you do

    int i = 128
    

    you end up with:

    i == 00000000 00000000 00000000 10000000
    

    When you cast it to a byte you the 24 most significative are truncated, so you end up with

    b == 10000000
    

    but a Java byte is signed, and 128 can't be represented, since it overflows and wraps around. So what happens is that the value ends up as 128 - 256 = -128 (that's because of two's complement).

提交回复
热议问题