StringHelper { public static byte[] hexStringToByteArray(String s) { if(s == null) { return null; } final int len = s.length(); final byte[] data = new byte[len / 2]; for (int i = 0; i < len; i += 2) { final int hiNibble = Character.digit(s.charAt(i), 16); final int loNibble = Character.digit(s.charAt(i+1), 16); if(hiNibble < 0 || loNibble < 0) { throw new IllegalArgumentException("no valid hex number at offset " + i); } data[i / 2] = (byte) ((hiNibble << 4) + loNibble); } return data; }  static String bytesToHexString(byte[] bytes); static byte[] hexStringToByteArray(String s);  }
@Test public void testHexStringToByteArray() { assertEquals(null, StringHelper.hexStringToByteArray(null)); assertEq(new byte[]{}, StringHelper.hexStringToByteArray("")); assertEq(new byte[]{0, 1, 2}, StringHelper.hexStringToByteArray("000102")); assertEq(new byte[]{14, 15, 16}, StringHelper.hexStringToByteArray("0E0F10")); assertEq(new byte[]{-128, -1}, StringHelper.hexStringToByteArray("80FF")); assertEq(new byte[]{26}, StringHelper.hexStringToByteArray("1a")); assertEq(new byte[]{-2}, StringHelper.hexStringToByteArray("fE")); try { StringHelper.hexStringToByteArray("1"); fail("exception expected"); } catch (Exception e) { } try { StringHelper.hexStringToByteArray("1X"); fail("exception expected"); } catch (Exception e) { } try { StringHelper.hexStringToByteArray("X1"); fail("exception expected"); } catch (Exception e) { } }