HexConverter { public static byte[] hexToBytes(String hexString) { if (hexString.length() % 2 != 0) { throw new IllegalArgumentException("Invalid number of digits: input must be a string of hexadecimal digit pairs"); } byte[] bytes = new byte[hexString.length() / 2]; for (int i = 0; i < bytes.length; i++) { bytes[i] = (byte) Integer.parseInt(hexString.substring(i * 2, i * 2 + 2), 16); } return bytes; } private  HexConverter(); static String bytesToHex(byte[] bytes); static byte[] hexToBytes(String hexString);  }
@Test public void testStringToBytes() { final byte[] correctAnswer = new byte[] { (byte) 166, (byte) 253, 0, 18, (byte) 184}; String hexString = "A6FD0012B8"; byte[] bytes = HexConverter.hexToBytes(hexString); assertEquals(bytes.length, correctAnswer.length); for (int i = 0; i < bytes.length; i++) assertEquals(correctAnswer[i], bytes[i]); }
@Test(expected = IllegalArgumentException.class) public void testWrongNumberOfDigits() { String hexString = "F5D"; HexConverter.hexToBytes(hexString); }
@Test(expected = IllegalArgumentException.class) public void testInvalidHexString() { String hexString = "A9G0"; HexConverter.hexToBytes(hexString); }