5

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)?

2 Answers 2

8

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();
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

This can be accomplished using ByteBuffer and ScatteringByteChannel like so :

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.