Convert hexadecimal string to byte in Java

In Java, how can I convert a hexadecimal string representation of a byte (like "1e") to a byte value?

For example:

byte b = ConvertHexStringToByte("1e"); 
+6
java string type-conversion byte
source share
3 answers

You can use Byte.parseByte("a", 16); but this will only work for values ​​up to 127, values ​​exceeding the values ​​that need to be done for the byte due to problems with the signature / unsigned so I recommend transferring it to int and then passing it to byte

 (byte) (Integer.parseInt("ef",16) & 0xff); 
+19
source share
 Integer.parseInt(str, 16); 
+15
source share

Byte.parseByte will return a byte by parsing the string representation.

Using a method with the signature (String, int) , radix can be specified as 16, so you can parse the hexadecimal representation of the byte:

 Byte.parseByte("1e", 16); 
+12
source share

All Articles