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
10000001
binary is 129
decimal. Ergo, it is bigger than Byte.MAX_VALUE
.
Your solution
byte b=(byte)0x81; //1000 0001
will result in b
having the value -127
. The same holds true for your workaround.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With