2011-08-01 73 views
5

我正在使用Naga库从套接字读取数据,该套接字产生通过委托函数接收的byte[]数组。解析一个字节数组到不同的数据类型?

我的问题是,我怎么能将这个字节数组转换为特定的数据类型,知道对齐?

例如,如果字节数组包含以下数据中,为了:

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

如何可以提取这些数据类型(在小端)?

回答

8

我建议你看看ByteBuffer类(特别是ByteBuffer.wrap方法和各种getXxx方法)。

实施例类

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(); 
    } 
} 
1

这可以使用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);