Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why Java throws a NumberFormatException

Tags:

java

exception

I got an exception while parsing a string to byte

String Str ="9B7D2C34A366BF890C730641E6CECF6F";

String [] st=Str.split("(?<=\\G.{2})");

byte[]bytes = new byte[st.length];
for (int i = 0; i <st.length; i++) {
 bytes[i] = Byte.parseByte(st[i]);
}
like image 838
Qaiser Mehmood Avatar asked Sep 17 '26 08:09

Qaiser Mehmood


2 Answers

That's because the default parse method expects a number in decimal format, to parse hexadecimal number, use this parse:

Byte.parseByte(st[i], 16);

Where 16 is the base for the parsing.

As for your comment, you are right. The maximum value of Byte is 0x7F. So you can parse it as int and perform binary AND operation with 0xff to get the LSB, which is your byte:

bytes[i] = Integer.parseInt(st[i], 16) & 0xFF;
like image 70
MByD Avatar answered Sep 18 '26 21:09

MByD


Assuming you want to parse the string as hexadecimal, try this:

bytes[i] = Byte.parseByte(st[i], 16);

The default radix is 10, and obviously B is not a base-10-digit.

like image 44
Paŭlo Ebermann Avatar answered Sep 18 '26 20:09

Paŭlo Ebermann