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)?
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();
}
}
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);
精彩评论