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

2019-01-14 14:09发布

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");

3条回答
聊天终结者
2楼-- · 2019-01-14 14:22
Integer.parseInt(str, 16);
查看更多
beautiful°
3楼-- · 2019-01-14 14:31

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);
查看更多
叼着烟拽天下
4楼-- · 2019-01-14 14:31

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);
查看更多
登录 后发表回答