2011-08-01 78 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);