Java program to convert Hex String to byte Array

In this tutorial, we will see a Java program to convert Hex String to byte Array.

Hexadecimal shortly known as Hex is a popular number system constituted of 16 units from the number 0 to 9 and alphabets A, B, C, D, E, F.

For encryption and to generate a SecretKey we need to convert the hex string to byte array.

The byte array will always be half of the size of the Hex string length because the a byte will always be formed from the pair of letters.

private byte[] hexToByte(String str){
    byte[] val = new byte[str.length() / 2];
    for (int i = 0; i < val.length; i++) {
        int index = i * 2;
        int j = Integer.parseInt(str.substring(index, index + 2), 16);
        val[i] = (byte) j;
    }
    return val;
}

hexToByte("123F92BCD");
// [18, 63, -110, -68]