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

1

5

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

Express answered 6/6, 2013 at 10:29 Comment(2)
Short answer: because byte is signed.Unsuccessful
Yes, I know it, the first 1 says that is a negative number. My point is that should not be a problem. How can I store -127 then, if I'm receiving an String?Express
C
7

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.

Cerebellum answered 6/6, 2013 at 10:32 Comment(1)
So it's just Byte.parseByte function is not capable of store a given byte, it needs to transform it to a number before. I thought it would do something like adding 1s and then shifting them. 0x81 is also 129 but it worksExpress

© 2022 - 2024 — McMap. All rights reserved.