Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Byte.parseByte("10000001",2) throws a NFE?

I have a bitmask to be stored in one byte, as I only need 8 bits. When I'm creating it I do it as a String (I thought it would be easier in this way) and then I transform it to a byte with Byte.parseByte(mask,2), but I found it does not work for certain values:

String bits="10000001";
Byte.parseByte(bits,2);// throws a NFE

But if I do:

byte b=(byte)0x81; //1000 0001

There is no problem.

PS: I found a workaround, byte b=(byte)Integer.parseInt(bits, 2);but anyway I want to know why I cannot convert 8 bits into a byte

like image 453
Pablo Lozano Avatar asked Jun 06 '13 10:06

Pablo Lozano


1 Answers

10000001 binary is 129 decimal. Ergo, it is bigger than Byte.MAX_VALUE.

Your solution

byte b=(byte)0x81; //1000 0001

will result in bhaving the value -127. The same holds true for your workaround.

like image 69
jlordo Avatar answered Sep 16 '22 12:09

jlordo