Convert a hex string to a byte in Java [closed]

2019-01-14 13:58发布

问题:

In Java, how can a hexadecimal string representation of a byte (e.g. "1e") be converted into a byte value?

For example:

byte b = ConvertHexStringToByte("1e");

回答1:

You can use Byte.parseByte("a", 16); but this will work only for values up to 127, values higher then that will need to cast to byte, due to signed/unsigned issues so i recommend to transfer it to an int and then cast it to byte

(byte) (Integer.parseInt("ef",16) & 0xff);


回答2:

Integer.parseInt(str, 16);


回答3:

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

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

Byte.parseByte("1e", 16);