Unpack byte array into different data types?

I use a library Nagato read data from a socket, which creates arrays byte[]that are accepted through the delegate function.

My question is, how can I convert this byte array to 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 these data types (in a bit endian )?

+5
source share
2 answers

I would advise you to take a look at the class ByteBuffer(in particular the method ByteBuffer.wrapand various methods getXxx).

Class 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();
    }
}
+8
source

, ByteBuffer ScatteringByteChannel :

ByteBuffer one = ByteBuffer.allocate(1);
ByteBuffer two   = ByteBuffer.allocate(1);
ByteBuffer three = ByteBuffer.allocate(2);
ByteBuffer four   = ByteBuffer.allocate(1);
ByteBuffer five = ByteBuffer.allocate(4);
ByteBuffer six   = ByteBuffer.allocate(4);

ByteBuffer[] bufferArray = { one, two, three, four, five, six };
channel.read(bufferArray);
+1

All Articles