【问题标题】:Populating data from a binary stream using byte array in java在java中使用字节数组从二进制流中填充数据
【发布时间】:2015-08-28 15:12:43
【问题描述】:

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

【问题讨论】:

  • 你的问题是?
  • 包一个包; // 如何在每次迭代中填充单个数据包 ??? ...

标签: java arrays binary byte decode


【解决方案1】:

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

【讨论】:

  • buffer.getInt() 会自动提取接下来的 4 个字节并处理字节序问题。
  • 是的。继承人的文档:docs.oracle.com/javase/7/docs/api/java/nio/ByteBuffer.html
  • 由于某种原因不会显示为超链接-.-
猜你喜欢
  • 1970-01-01
  • 2019-05-19
  • 1970-01-01
  • 1970-01-01
  • 2011-11-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多