0

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();
}
  • *String textRead = new String(reply, 0, bytesRead);* You seem to be creating strings. That would be ok if the source is string-based but 7E2466490CE1A430 is certainly not a valid UTF-8 string. Also, BCD is for encoding *digits*, not arbitrary strings, so I'm not sure where you're going with all this... – g00se Feb 03 '23 at 11:38
  • Actually, our client will send the message in BCD format, which I need to receive and convert it back to HEX. I wrote the client in this example as a test program, so I could test it. – Mohamed Nazir Feb 03 '23 at 13:59
  • *which I need to receive and convert it back to HEX.* Why would you convert digits to hex? That would take up twice as much space and be not readily readable. `01` would become `3031` – g00se Feb 03 '23 at 14:20

1 Answers1

0

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));
}