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;
For example, received message is
0xFA 0xF8 0x1B 0x01 0x81 0x60 0x33 0x3C
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
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);