I need to process streamed binary data (QDataStream) of defined structure created by another non-Qt program. I wonder what is the best practice to interpret that data. Let's say the data is structured (struct definition provided) in telegrams as follows and cannot be changed by myself:
4 bytes header | 2 bytes sequence number | 1 byte checksum | 10 bytes data
I see the following possibilities to handle the data in a "Telegram" class:
- The Telegram class has a private QByteArray member variable. All data (17 bytes) is read at once from the stream with the readRawData method and stored in there. The variables are accessed and interpreted with public methods like
return (array.at(4)<<8) + array.at(5)
for the sequence number, with is not very elegant. - The Telegram class has a public char[17] member variable in union with a struct. All data is read from the stream with readRawData and stored in there. When accessing the variables after, this is done only over the struct, like
telegramstruct.squenceNumber
I see potential problems with this method like endianness and padding. - The Telegram class has private member variables for each of the telegram fields like
QString strHeader
. When reading the telegrams from the stream, data is stored directly in these variables. Reading is done with readRawData or with the operator>> for basic types.
The code should be as fast as possible since there is a lot of data to process. I am using Qt 5.0.1 on Windows with MinGW.
My questions:
- Which one of the above solutions is best practice and fast, or is there a better way?
- Is reading all at once like in 1 faster than reading 4 bytes, 2 bytes, 1 byte, ... like in 3?
- With 1 and 3, I cannot use a provided header file with a defined struct, would that be bad practice?
- Is it somehow possible to have kind of a "union" with QByteArray and a structure?
- How would I easily calculate the checksum with solution 3?
Thanks a lot for your opinions and hints.
Chris