Dissect a byte array into distinct data types?

I am using the Naga library to read data from a socket, which produces byte[] arrays which are received via a delegate function.

My question is, how can I convert this byte array into specific data types, knowing the alignment?

For example, if the byte array contains the following data, in order:

| byte | byte | short | byte | int | int |

How can I extract those data types (in little endian)?

Answer

I’d suggest you have a look at the ByteBuffer class (specifically the ByteBuffer.wrap method and the various getXxx methods).

Example class:

class Packet {

    byte field1;
    byte field2;
    short field3;
    byte field4;
    int field5;
    int field6;

    public Packet(byte[] data) {
        ByteBuffer buf = ByteBuffer.wrap(data)
                                   .order(ByteOrder.LITTLE_ENDIAN);

        field1 = buf.get();
        field2 = buf.get();
        field3 = buf.getShort();
        field4 = buf.get();
        field5 = buf.getInt();
        field6 = buf.getInt();
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *