NumberFormatException when converting from string to byte

I find a strange thing. I have a binary number as a string, in particular "01001100". But I get the exception mentioned above by executing the following code.

String s = "01001100"; byte b = Byte.parseByte(s); 
But why is it happening? Whereas in a byte we can store max no. upto 127 and min. upto -128.
And the decimal equivalent of the above number is 76 which is perfectly in the range.

The special exception that I get is this:

java.lang.NumberFormatException: value out of range. value: 01001100 radix: 10

Is there any way to get rid of it. Yes, and I am required to use a byte only if I only extract data stored in image bytes by byte.
Thanks.

+6
java byte
source share
2 answers

The key is at the end of the exception line: radix:10 . You are converting the decimal value of 1 001 100 to bytes, and it does not fit. Try the following:

 String s = "01001100"; byte b = Byte.parseByte(s, 2); 
+12
source share

01001100 is a fairly large number in decimal form (more than a million, see the docs for parseByte(String) ). You probably want a version that accepts radix :

 byte b = Byte.parseByte(s, 2); 
+4
source share

All Articles