Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

-128 as binary literal in Java

Tags:

java

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?

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

My understanding is that 1000000 should be -128 but java indicates the notok variable above should be an int and not a byte

like image 216
imrichardcole Avatar asked Jan 29 '16 07:01

imrichardcole


1 Answers

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;
like image 184
Eng.Fouad Avatar answered Oct 16 '22 17:10

Eng.Fouad