-128 as binary literal in Java

后端 未结 2 1430
暗喜
暗喜 2021-01-12 02:04

Based on the fact that a byte type in java is a signed 8 bit two\'s complement integer, why doesn\'t the second way of declaring a byte work?

b         


        
2条回答
  •  佛祖请我去吃肉
    2021-01-12 02:38

    Actually, as mentioned by Eng Fouad, 0b10000000 is an integer literal. Integer literals create an int value, the size of which in Java is 32-bit.The byte data type is an 8-bit signed two's complement integer.

    So assigning the integer literal to a byte type would not work. To create a conversion between two incompatible types, one must use a cast.

     b = (byte)0b10000000;        // (This is narrowing conversion)
    

    Also, the signed 2's complement representation of -128 is 110000000. But, the MSB 's 1 can be discarded(represents negative sign bit) and hence 10000000 is acceptable as 2's complement representation of -128.

提交回复
热议问题