In Java, how do I convert a hex string to a byte[]? [duplicate]

The accepted answer does not consider leading zeros which may cause problems

This question answers it. Depending on whether you want to see how its done or just use a java built-in method. Here are the solutions copied from this and this answers respectively from the SO question mentioned.

Option 1: Util method

public static byte[] hexStringToByteArray(String s) {
    int len = s.length();
    byte[] data = new byte[len / 2];
    for (int i = 0; i < len; i += 2) {
        data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
                             + Character.digit(s.charAt(i+1), 16));
    }
    return data;
}

Option 2: One-liner build-in

import javax.xml.bind.DatatypeConverter;

public static String toHexString(byte[] array) {
    return DatatypeConverter.printHexBinary(array);
}

public static byte[] toByteArray(String s) {
    return DatatypeConverter.parseHexBinary(s);
}

Leave a Comment