-128 as a binary literal in Java

Based on the fact that the byte type in java is a signed 8-bit two integer padding , why not the second way to declare a byte job?

 byte ok = -128; byte notok = 0b10000000; 

I understand that 1000000 should be -128 , but java indicates that the notok variable above should be int , not byte

+7
java
source share
2 answers

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

 byte notok = (byte) 0b10000000; 
+7
source share

Actually, as indicated by Eng Fouad , 0b10000000 is a whole literal. Integer literals create an int value whose size in Java is 32-bit. The byte data type is an 8-bit two-digit integer.

Thus, assigning an integer literal to a byte type will not work. To create a conversion between two incompatible types, you must use a listing.

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

In addition, a signed submission with two additions is -128 110000000 . But MSB 1 can be dropped (represents a negative sign bit), and therefore 10,000,000 is acceptable as 2 additional representations of -128.

+4
source share

All Articles