Convert a hex string to a byte in Java

byte, java, string, type-conversion

Solution

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

Problem

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

Original source

Related problems