Hex { public static final byte[] decode(final String hex) { if (hex.length() > 0 && hex.length() % 2 != 0) { throw new IllegalArgumentException("Odd number of characters: " + hex); } final byte[] bytes = new byte[hex.length() / 2]; for (int i = 0, j = 0; i < bytes.length; i++) { int digit = toDigit(hex.charAt(j++)); bytes[i] = (byte) (digit << 4); digit = toDigit(hex.charAt(j++)); bytes[i] |= digit; } return bytes; } private  Hex(); static final String encode(int i); static final String encode(final byte b); static final String encode(final byte[] b); static final byte[] decode(final String hex);  }
@Test(expected = IllegalArgumentException.class) public final void testDecodeOddString() { Hex.decode("123"); }
@Test public final void testDecodeEmptyString() { final byte[] expecteds = new byte[0]; final byte[] actuals = Hex.decode(""); Assert.assertArrayEquals(expecteds, actuals); }
@Test(expected = NullPointerException.class) public final void testDecodeNull() { Hex.decode(null); }
@Test(expected = IllegalArgumentException.class) public final void testDecodeWithIllegalCharacter() { Hex.decode("12G3"); }
@Test public final void testDecodeOneByte() { for (int i = Byte.MIN_VALUE; i <= Byte.MAX_VALUE; i++) { final byte[] expecteds = new byte[] { (byte) i }; final String hexString = String.format("%02x", Integer.valueOf(i & 0xFF)); Assert.assertArrayEquals(expecteds, Hex.decode(hexString.toLowerCase())); Assert.assertArrayEquals(expecteds, Hex.decode(hexString.toUpperCase())); } }
@Test public final void testDecodeMoreBytes() { for (int i = Byte.MIN_VALUE, j = Byte.MAX_VALUE; i <= Byte.MAX_VALUE; i++, j--) { final byte[] expecteds = new byte[] { (byte) i, (byte) j }; String hexString = String.format("%02x", i & 0xFF); hexString += String.format("%02x", j & 0xFF); Assert.assertArrayEquals(expecteds, Hex.decode(hexString.toLowerCase())); Assert.assertArrayEquals(expecteds, Hex.decode(hexString.toUpperCase())); } }