Explicit conversion from int to byte in Java

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

    Bytes are treated as signed values in Java; like you pointed out, the range of a byte is [-128,127]. Adding 1 to 127 flips the sign bit, which means that 127 + 1 = -128.

提交回复
热议问题