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

时间:2015-06-12 14:47:05

标签: 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 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++;
}

1 个答案:

答案 0 :(得分:0)

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