Q: Convert a string representation of a hex dump to a byte array using Java?

D: I am looking for a way to convert a long string (from a dump), that represents hex values into a byte array. I couldn't have phrased it better than the person that posted the same question here: http://www.experts-exchange.com/Programming/Programming_Languages/Java/Q_21062554.html But to keep it original, I'll phrase it my own way: suppose I have a string "00A0BF" that I would like interpreted as the byte[] {0x00,0xA0,0xBf} what should I do? I am a Java novice and ended up using BigInteger and watching out for leading hex zeros. But I think it is ugly and I am sure I am missing something simple...

Test Case #1


File ID: #140861-0-cc


class Util {
    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;
    }
}

  1. "0" is not valid input. Bytes require two hexidecimal digits each. As the answer notes, "Feel free to add argument checking...if the argument is not known to be safe."
  2. Javax.xml.bind.DatatypeConverter.parseHexBinary(hexString) seems to be about 20% faster than the above solution in my micro tests (for whatever little they are worth), as well as correctly throwing exceptions on invalid input (e.g. "gg" is not a valid hexString but will return -77 using the solution as proposed).
  3. It doesn't work for the String "0"". It throws an java.lang.StringIndexOutOfBoundsException

Comments Quality
Accurate?:
Precise?:
Concise?:
Useful?: