在java中使用字节数组从二进制流填充数据

在java中使用字节数组从二进制流填充数据,java,arrays,binary,byte,decode,Java,Arrays,Binary,Byte,Decode,我想从字节数组中提取特定的位和字节。字节数组使用文件输入流填充,并在特定长度的流中包含连续重复数据包格式,例如标头时间戳数据类型数据crc。我需要填充一个数据包列表,并能够从中提取数据 Packet() { byte header; // 1 BYTE: split into bit flags, and extracted using masks int timestamp; // 4 BYTES int dataType; // 1 BYTE string d

我想从字节数组中提取特定的位和字节。字节数组使用文件输入流填充,并在特定长度的流中包含连续重复数据包格式,例如标头时间戳数据类型数据crc。我需要填充一个数据包列表,并能够从中提取数据

Packet()
{
    byte header; // 1 BYTE: split into bit flags, and extracted using masks
    int timestamp; // 4 BYTES
    int dataType; // 1 BYTE
    string data; // 10 BYTES
    int crc; // 1 BYTE
}

static final int PACKET_SIZE 17 // BYTES
Packet[] packets;
byte[] input = new byte[(int)file.length()];
InputStream is = new BufferedInputStream(new FileInputStream(file));
int totalBytesRead = 0;
int totalPacketsRead = 0;
while(totalBytesRead < input.length)
{
    int bytesRemaining = input.length - totalBytesRead;         
    int bytesRead = input.read(result, totalBytesRead, PACKET_SIZE); 
    totalBytesRead = totalBytesRead + bytesRead;

    packet aPacket;
    // How to populate a single packet in each iteration ???
    ...
    packets[totalPacketsRead] = aPacket;
    totalPacketsRead++;
}
Packet()
{
字节头;//1字节:拆分为位标志,并使用掩码提取
int timestamp;//4字节
int数据类型;//1字节
字符串数据;//10字节
int crc;//1字节
}
静态最终整型数据包\u大小17//字节
数据包[]数据包;
字节[]输入=新字节[(int)file.length()];
InputStream is=new BufferedInputStream(new FileInputStream(file));
int totalBytesRead=0;
int totalPacketsRead=0;
while(totalBytesRead
您可以使用
ByteBuffer

ByteBuffer buffer = ByteBuffer.wrap(packetBuffer);

Packet packet = new Packet();
packet.header = buffer.get();
packet.timestamp = buffer.getInt();
...
或者,如果您愿意:从单个字节生成整数,如下所示:

public int readInt(byte[] b , int at)
{
    int result = 0;

    for(int i = 0 ; i < 4 ; i++)
        result |= ((int) b[at + i]) << ((3 - i) * 8);

    return result;
} 
public int readInt(字节[]b,int at)
{
int结果=0;
对于(int i=0;i<4;i++)

结果|=((int)b[at+i]),您的问题是?packet aPacket;//如何在每次迭代中填充单个数据包???…将缓冲.getInt()自动提取接下来的4个字节,并处理endian问题。是的。以下是文档:docs.oracle.com/javase/7/docs/api/java/nio/ByteBuffer.htmlwhich,由于某些原因不会显示为hyperlink--