-128 as binary literal in Java

后端 未结 2 1411
暗喜
暗喜 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.

    0 讨论(0)
  • 2021-01-12 02:41

    0b10000000 is an int literal (= 0b00000000000000000000000010000000) which equals to +128. byte holds 8 bits and cannot represent +128. However, you can achieve this as follows:

    byte notok = (byte) 0b10000000;
    
    0 讨论(0)
提交回复
热议问题