2011-08-01 11 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

これはそうようByteBufferScatteringByteChannelを用いて達成することができる。

 
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); 
関連する問題