public static byte[] hexStringToByteArray(String hexEncodedBinary) {
        if (hexEncodedBinary.length() % 2 == 0) {
            char[] sc = hexEncodedBinary.toCharArray();
            byte[] ba = new byte[sc.length / 2];

            for (int i = 0; i < ba.length; i++) {
                int nibble0 = Character.digit(sc[i * 2], 16);
                int nibble1 = Character.digit(sc[i * 2 + 1], 16);
                if (nibble0 == -1 || nibble1 == -1){
                    throw new IllegalArgumentException(
                    "Hex-encoded binary string contains an invalid hex digit in '"+sc[i * 2]+sc[i * 2 + 1]+"'");
                }
                ba[i] = (byte) ((nibble0 << 4) | nibble1);
            }

            return ba;
        } else {
            throw new IllegalArgumentException(
                    "Hex-encoded binary string contains an uneven no. of digits");
        }
    }
@Test
    public void testHexStringToByteArray() throws Exception {
        byte [] ba;
        ba = BinaryTCPClientImpl.hexStringToByteArray("");
        assertEquals(0, ba.length);

        ba = BinaryTCPClientImpl.hexStringToByteArray("00");
        assertEquals(1, ba.length);
        assertEquals(0, ba[0]);

        ba = BinaryTCPClientImpl.hexStringToByteArray("0f107F8081ff");
        assertEquals(6, ba.length);
        assertEquals(15, ba[0]);
        assertEquals(16, ba[1]);
        assertEquals(127, ba[2]);
        assertEquals(-128, ba[3]);
        assertEquals(-127, ba[4]);
        assertEquals(-1, ba[5]);
        try {
            ba = BinaryTCPClientImpl.hexStringToByteArray("0f107f8081ff1");// odd chars
            fail("Expected IllegalArgumentException");
        } catch (IllegalArgumentException expected){
            // ignored
        }
        try {
            BinaryTCPClientImpl.hexStringToByteArray("0f107xxf8081ff"); // invalid
            fail("Expected IllegalArgumentException");
        } catch (IllegalArgumentException expected){
            // ignored
        }
    }