Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JAVA: why binary literal for byte with negative sign is being considered as integer type?

Tags:

java

I can't understand the following behavior.

I'm trying to declare byte mask using binary literal:

byte mask = 0b1111_1111;

But that's not possible, because I get the following error message:

Type mismatch: cannot convert from int to byte

The most interesting thing is that when I try to declare the mask directly, in decimal representation

byte mask = -1;

I get no error, but these two representations should be absolutely equal!

What am I doing wrong? Thanks in advance.

like image 439
Kirill Smirnov Avatar asked Sep 18 '13 10:09

Kirill Smirnov


1 Answers

You can safely assign a values from -2^7 to 2^7-1 (-128 to 127) to a byte ,since it is 8 bits.

where as 0b1111_1111 = 255

So need a cast there

 byte mask = (byte) 0b1111_1111;
like image 151
Suresh Atta Avatar answered Nov 10 '22 20:11

Suresh Atta