NumberFormatException while converting from string to byte

Discussion DashboardCategory: JavaNumberFormatException while converting from string to byte
dknitk asked 8 years ago
DHARMEDRA SAHU Staff replied 8 years ago

You can convert you string to Integer first and convert Integer to Byte. This will work wihout throwing any exception.

Byte byteValue = Integer.valueOf(“123453”);

1 Answers
DHARMEDRA SAHU Staff answered 8 years ago

I saw below post on Stacktrace but did not get any proper solution.

I am coming across a strange thing. I have a number in binary in the form of string particularly “01001100”. But I am getting 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 particular exception I am getting is as:

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

Is there any way to get rid of it. Yes and it is compulsory for me to use byte only as I am extracting the data stored in the image byte by byte only.
Thank you.