views:

161

answers:

2

Is this the best way to convert String hex to bytes? Or can you think a shorter/simpler?

public static byte[] hexToBytes(String hex) {
return hexToBytes(hex.toCharArray());
}

public static byte[] hexToBytes(char[] hex) {
int length = hex.length / 2;
byte[] raw = new byte[length];
for (int i = 0; i < length; i++) {
    int high = Character.digit(hex[i * 2], 16);
    int low = Character.digit(hex[i * 2 + 1], 16);
    int value = (high << 4) | low;
    if (value > 127)
    value -= 256;
    raw[i] = (byte) value;
}
return raw;
}
+4  A: 
byte[] yourBytes = new BigInteger(hexString, 16).toByteArray();
Taylor Leese
which would be the max hexString lenght supported?
Tom Brito
BitInteger handles arbitrary-precision integers so it should be any size.
Taylor Leese
A: 

You don't need the subtraction of 256 when the value is greater than 127. Just cast the value to a byte. For example, byte b = (byte) 255 assigns a value of -1 to b.

A narrowing conversion on integer types simply discards the high-order bits that don't fit in the target type.

erickson