Search code examples
javahexbcd

Hexa to BCD conversion


I have the HEXA String as 7E2466490CE1A430 which I am converting into BCD and sending this value from a TCP client program.

 String message = "7E2466490CE1A430";
 byte[] result = Hex.decodeHex(message);

Socket socket = SocketFactory.getDefault().createSocket(HOST, PORT);
socket.getOutputStream().write(result);

On the other side of my TCP server, I am consuming this byte[] and converting it back to HEX, but, the value has changed to 7E2466490CEFBFBD30, and Any Idea what I am doing wrong?

  public void deserialize(InputStream inputStream) throws IOException {
    byte[] reply = new byte[1024];
    int bytesRead;

    while (-1 != (bytesRead = inputStream.read(reply))) {
        String textRead = new String(reply, 0, bytesRead);
        String message = convertStringToHex(textRead);
        LOGGER.info("MESSAGE ::"+ message);
    }
}

public static String convertStringToHex(String str) {
    StringBuilder sb = new StringBuilder();
    for (byte b : str.getBytes(StandardCharsets.UTF_8)) {
        sb.append(String.format("%02X", b));
    }
    return sb.toString();
}

Solution

  • Try below change to deserialize() method

    public void deserialize(InputStream inputStream) throws IOException {
        byte[] reply = new byte[1024];
        int bytesRead;
        while (-1 != (bytesRead = inputStream.read(reply))) {
            String message = Hex.encodeHexString (reply);
            LOGGER.info("MESSAGE ::"+ message);
        }
    }
    

    encodeHexString() is used from below library

    https://github.com/apache/commons-codec/blob/master/src/main/java/org/apache/commons/codec/binary/Hex.java

    /**
     * Converts an array of bytes into a String representing the hexadecimal values of each byte in order. The returned
     * String will be double the length of the passed array, as it takes two characters to represent any given byte.
     *
     * @param data a byte[] to convert to hex characters
     * @return A String containing lower-case hexadecimal characters
     * @since 1.4 strong text
     */
    public static String encodeHexString(final byte[] data) {
        return new String(encodeHex(data));
    }