ByteBufferDumper { public static ByteBuffer fromHexString(String hex) { if (hex.length() % 2 != 0) { throw new IllegalArgumentException("the hexa-decimal string length cannot be odd"); } int size = hex.length() / 2; ByteBuffer res = ByteBuffer.allocate(size); for (int i = 0; i < size; i++) { int b = Integer.parseInt(hex.substring(i*2, i*2 + 2), 16); if (Integer.highestOneBit(b) == 128) { b = b - 256; } res.put((byte) b); } res.flip(); return res; }  static String dump(ByteBuffer buffer, int nbBytes, boolean toAscii); static String dump(ByteBuffer buffer); static String toHex(ByteBuffer buffer); static ByteBuffer fromHexString(String hex);  }
@Test public void checkFromHexStringEmptyStringReturnsEmptyByteArray() { ByteBuffer buffer = ByteBufferDumper.fromHexString(""); assertEquals(0, buffer.remaining()); }
@Test public void checkFromHexStringNormalStringReturnsByteArray() { ByteBuffer buffer = ByteBufferDumper.fromHexString("ff"); assertEquals(1, buffer.remaining()); assertEquals(-1, buffer.get()); }
@Test public void checkFromHexStringNormalStringUppercaseReturnsByteArray() { ByteBuffer buffer = ByteBufferDumper.fromHexString("FF"); assertEquals(1, buffer.remaining()); assertEquals(-1, buffer.get()); }
@Test(expected=NumberFormatException.class) public void checkFromHexStringInvalidStringReturnsException() { ByteBuffer buffer = ByteBufferDumper.fromHexString("non-hexastring"); assertEquals(1, buffer.remaining()); assertEquals(-1, buffer.get()); }