Java 将字节数组分解为不同的数据类型?

Java 将字节数组分解为不同的数据类型?,java,Java,我正在使用Naga库从套接字读取数据,该套接字生成byte[]数组,这些数组通过委托函数接收 我的问题是,在知道对齐方式的情况下,如何将这个字节数组转换为特定的数据类型 例如,如果字节数组包含以下数据,则按顺序排列: 如何提取这些数据类型(在little endian中)?我建议您看看ByteBuffer类(特别是方法和各种getXxx方法) 示例类: class Packet { byte field1; byte field2; short field3;

我正在使用
Naga
库从套接字读取数据,该套接字生成
byte[]
数组,这些数组通过委托函数接收

我的问题是,在知道对齐方式的情况下,如何将这个字节数组转换为特定的数据类型

例如,如果字节数组包含以下数据,则按顺序排列:


如何提取这些数据类型(在little endian中)?

我建议您看看
ByteBuffer
类(特别是方法和各种
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();
    }
}

这可以通过如下方式实现:

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); ByteBuffer one=ByteBuffer.allocate(1); ByteBuffer 2=ByteBuffer.allocate(1); ByteBuffer三=ByteBuffer.allocate(2); ByteBuffer四=ByteBuffer.allocate(1); ByteBuffer five=ByteBuffer.allocate(4); ByteBuffer六=ByteBuffer.allocate(4); ByteBuffer[]bufferArray={1,2,3,4,5,6}; 通道读取(缓冲阵列); 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);