Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dissect a byte array into distinct data types?

Tags:

java

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

like image 528
Kristina Brooks Avatar asked Aug 01 '11 14:08

Kristina Brooks


2 Answers

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();
    }
}
like image 154
aioobe Avatar answered Sep 30 '22 23:09

aioobe


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);
like image 39
arun_suresh Avatar answered Oct 01 '22 00:10

arun_suresh