Here is a useful method to convert a hexadecimal to binary using Java. If you may wonder why the HEX_String object contains 0 to 9 and A to F, it is because a hexadecimal or base-16 notation uses 16 different digits: 0 up to 9 and then the letters A, B, C, D, E, F to represent 10, 11, 12, 13, 14 and 15.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
String HEX_STRING = "0123456789ABCDEF"; public static byte[] convertHexadecimal2Binary(byte[] hex) { int block = 0; byte[] data = new byte[hex.length / 2]; int index = 0; boolean next = false; for (int i=0; i<hex.length; i++) { block <<= 4; int pos = HEX_STRING.indexOf(Character.toUpperCase((char) hex[i])); if (pos > -1) block += pos; if (next) { data[index] = (byte)(block & 0xff ); index++; next = false; } else next = true; } return data; } |