繁体   English   中英

使用Java中的字节数组从二进制流填充数据

[英]Populating data from a binary stream using byte array in java

我想从字节数组中提取特定的位和字节。 字节数组使用文件输入流填充,并且在特定长度的流中包含连续的重复数据包格式,例如header-timestamp-datatype-data-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++;
}

您可以使用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;
} 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM