Populating data from a binary stream using byte array in java

430 views Asked by At

I want to extract particular bits and bytes from a byte-array. The byte-array got populated using a file input stream, and contains continuous repetive data packet format in the stream of particular length, e.g. header-timestamp-datatype-data-crc. I need to populate a list of the packets, and be able to extract the data from it.

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

There are 1 answers

3
AudioBubble On

You could use ByteBuffer:

ByteBuffer buffer = ByteBuffer.wrap(packetBuffer);

Packet packet = new Packet();
packet.header = buffer.get();
packet.timestamp = buffer.getInt();
...

Or if you prefer: generate integers from the single bytes like this:

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;
}