QDataStream pack and unpack
-
I am trying to write a function to pack/unpack data from/to qdatastream.
void pack(QDataStream& myStream, quint64 data, int size)
to copy size bits of data to myStream. Each bit of data can be stored as 1 byte of data in myStream.
In similar way, I am trying to write another function to unpack data from stream
quint64 unpack(QDataStream& myStream, int size)
to unpack size bits data from myStream, and the return value is quint64.
I can do it without funciton, but with function, I have no idea how to write these two.
Any help? -
main:
QDataStream dataStream;
pack(dataStream, 0x123, 12);
The Stream should have these information: pack 0001 0010 0011 to the dataStream
0000 0001 0000 0001 0000 0000 0000 0000 0000 0000 0000 0001 0000 0000 0000 0000 0000 0001 0000 0000 0000 0000 0000 0000.
1 byte of stream will represent 1 bit in data as this sequence: 1100 0100 1000 (LSB to MSB).
When I unpack the dataStream by using funciton: unpack(dataStream, 4), the process will be in inverted order:
assigned every byte from dataStream to a bit of data. The data taken out from stream and remaining stream will be:
data: 0011 = 3
0000 0001 -->1
0000 0001 -->1
0000 0000 -->0
0000 0000 -->0
remaining stream:0001 0010 = 12
0000 0000 0000 0001 0000 0000 0000 0000 0000 0001 0000 0000 0000 0000 0000 0000.
Note: when packing data, it will add the data to the right, and unpackData, the data will be removed from the left of the stream. -
Anyway,
http://doc.qt.io/qt-5/qdatastream.html#writeRawData
for(;data;data/=static_cast<quint64>(2)){ const qint8 byte= data%2; myStream.writeRawData(&byte,1); }