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++;
}
You could use
ByteBuffer
:Or if you prefer: generate integers from the single bytes like this: