Search code examples
javastructbinarybuffer

how to read the given binary struct using java?


I'm trying to decode and read binary data sent from a device, I need to extract a decimal number which is inside the binary structure. this is the structure detail:

(2) Synchronization message format

typedef struct {
    WORD SyncHeader;
    WORD SyncID;
    DWORD UnitID;
} SyncStruct;
  • SyncHeader is always 0xf8fa
  • SyncID is a message sequence number
  • UnitID is the unit identification number

For example, received message is

0xFA 0xF8 0x1B 0x01 0x81 0x60 0x33 0x3C

  • SyncHeader = 0xF8 0xFA
  • SyncID = 0x01 0x1B (Decimal = 283)
  • UnitID = 0x3C 0x33 0x60 0x81 (Decimal = 1010000001)

now, having the structure well defined, I have a small java code that reads a different structure but implements the same principle:

private String getId(ChannelBuffer buf) {

    String id = "";
    for (int i = 0; i < 7; i++) {
        int b = buf.getUnsignedByte(i);

        // First digit
        int d1 = (b & 0xf0) >> 4;
        if (d1 == 0xf) break;
        id += d1;

        // Second digit
        int d2 = (b & 0x0f);
        if (d2 == 0xf) break;
        id += d2;
    }

    return id;
}

What modifications do I have to apply to my small java code in order to read and store in a variable just the SyncID message sequence number which is a decimal value?

Thanks


Solution

  • Put your bytes in a byte array and use ByteBuffer to read numbers from it

        ByteBuffer bb = ByteBuffer.wrap(byteArray);
        int syncHeader =  bb.getShort();
        int syncId =  bb.getShort();
        int unitId = bb.getInt();
    

    it is also possible to read only syncId

        ByteBuffer bb = ByteBuffer.wrap(byteArray);
        int syncId =  bb.getShort(2);