Search code examples
javastringhexconcatenationchecksum

Java hex string concatenate checksum


I want to send a hex message to a device with check sum in java.

    String msg = "\u0002\u0053\u003F\u0003";
    String checksum = "\u00EE";
    String last = "\u0004";
    msg = msg + checksum + last;
    sendmessage(msg);

If I hardcode the check sum as above it works. But if I insert check sum dynamically, it doesn't. This is what I have tried

String msg = "\u0002\u0053\u003F\u0003";
String checksum = String.format("\\u00%2X",238); // decimal 238 = Hex \u00EE
String last = "\u0004";
msg = msg + checksum + last;
sendmessage(msg) ; //getting invalid checksum because it is not inserted properly

Any directions please?


Solution

  • The \uxxxx syntax is processed by the Java compiler, it is not literal. It sounds like you want simply:

    String msg = "\u0002\u0053\u003F\u0003";
    char checksum = (char)238;
    String last = "\u0004";
    msg = msg + checksum + last;
    sendmessage(msg);