If I had a byte stream which is encoded with the following format:
0x20 Length D_1 D_2 ... D_n CS
0x20...marks the beginning of a data frame
Length...number of bytes following
D_1-D_n...data bytes (interpreted as signed ints)
CS...One Byte Checksum
Example:
0x20 0x05 0x01 0x02 0xD1 0xA1 0xAF
0x20 0x05 0x12 0x03 0x02 0x3A 0xF2
...
...
How would I decode this byte stream from an InputStream in a way which is common and efficient? My idea is to use a BufferedInputStream and the following procedure (in pseudo code):
BufferedInputStream bufIS = new BufferedInputStream(mInStream);
while (true ) {
byte startFrame = bufIS.read();
if(startFrame == 0x20) { //first byte must mark the beginning of a data frame
int length = bufIS.read();
byte dataframe[] = new bye[length];
for (int i = 0; i<length i++) { //read data bytes
dateframe[i] = bufIS.read();
}
if(verifyChecksum(bufIS.read()) postEvent(dataframe);
}
}
Is this an appropriate way for receiving the data frames from the InputStream? I cant't think of a better solution for this. Also there's an alternative read(byte[] b, int off, int len) method which reads chunks of bytes from the stream but it's not guaranteed that len number of bytes are read, so i think this is not helpful in my case.
new byte[]as well as in yourforloop you have to replacelengthwithlength - 1. I'd still go with using theread(byte[],int,int)function (repeatedly). The number of bytes actually read is returned by this function, so you can tell if you have to invoke it another time, or if there was some error in the stream (premature end of data).