HexUtil { public static byte[] toByteArray(CharSequence hexString) { if (hexString == null) { return null; } return toByteArray(hexString, 0, hexString.length()); }  static String toHexString(byte[] bytes); static String toHexString(byte[] bytes, int offset, int length); static void appendHexString(StringBuilder buffer, byte[] bytes); static void appendHexString(StringBuilder buffer, byte[] bytes, int offset, int length); static String toHexString(byte value); static void appendHexString(StringBuilder buffer, byte value); static String toHexString(short value); static void appendHexString(StringBuilder buffer, short value); static String toHexString(int value); static void appendHexString(StringBuilder buffer, int value); static String toHexString(long value); static void appendHexString(StringBuilder buffer, long value); static int hexCharToIntValue(char c); static byte[] toByteArray(CharSequence hexString); static byte[] toByteArray(CharSequence hexString, int offset, int length); static char[] HEX_TABLE; }
@Test public void toByteArray() throws Exception { byte[] bytes = null; bytes = HexUtil.toByteArray(null); Assert.assertArrayEquals(null, bytes); bytes = HexUtil.toByteArray(""); Assert.assertArrayEquals(new byte[] { }, bytes); bytes = HexUtil.toByteArray("65"); Assert.assertArrayEquals(new byte[] { 0x65 }, bytes); bytes = HexUtil.toByteArray("fF"); Assert.assertArrayEquals(new byte[] { (byte)0xFF }, bytes); bytes = HexUtil.toByteArray("BbCc"); Assert.assertArrayEquals(new byte[] { (byte)0xbb, (byte)0xcc }, bytes); bytes = HexUtil.toByteArray("AaBbCcDdEefF"); Assert.assertArrayEquals(new byte[] { (byte)0xaa, (byte)0xbb, (byte)0xcc, (byte)0xdd, (byte)0xee, (byte)0xff }, bytes); }
@Test public void toByteArrayWithOffsetAndLength() throws Exception { byte[] bytes = null; bytes = HexUtil.toByteArray(null, 0, 2); Assert.assertArrayEquals(null, bytes); bytes = HexUtil.toByteArray("", 0, 0); Assert.assertArrayEquals(new byte[] { }, bytes); bytes = HexUtil.toByteArray("65", 0, 2); Assert.assertArrayEquals(new byte[] { 0x65 }, bytes); bytes = HexUtil.toByteArray("fF", 0, 2); Assert.assertArrayEquals(new byte[] { (byte)0xFF }, bytes); bytes = HexUtil.toByteArray("AaBbCcDdEefF", 2, 4); Assert.assertArrayEquals(new byte[] { (byte)0xbb, (byte)0xcc }, bytes); bytes = HexUtil.toByteArray("AaBbCcDdEefF", 0, 12); Assert.assertArrayEquals(new byte[] { (byte)0xaa, (byte)0xbb, (byte)0xcc, (byte)0xdd, (byte)0xee, (byte)0xff }, bytes); }