Reputation: 1069
I'm going to receive length delimited frame from server with QTcpSocket in this format:-
+----------+--------------------------------+
| len: u32 | frame payload |
+----------+--------------------------------+
where u32 is in 32 bit unsigned integer encoded in Big-Endian format. depending on config, It can also be Little Endian But I will know about endianness beforehand on client side.
How can I convert first 4 bytes of this char*
array or QByteArray
to 32 bit unsigned int ?
After reading the frame I will need to send message in same format. So If I have message of length 20 bytes, How can I write 20 as 32 bit unsigned int to QByteArray or char* in Big/Little endian format ?
Upvotes: 3
Views: 4416
Reputation: 73041
You can use Qt's QtEndian utility functions to accomplish that.
For example, if you have a quint32
(or uint32_t
) and want to write that value in little-endian format to the first four bytes of a char array:
const quint32 myValue = 12345;
char frameBuffer[256];
qToLittleEndian(myValue, frameBuffer);
... or, alternatively, to read the first four bytes of a char array in as a little-endian quint32
(or uint32_t
):
const char frameBuffer[256] = {0x01, 0x00, 0x00, 0x00};
quint32 myValue = qFromLittleEndian<quint32>(frameBuffer);
Big-endian reads/writes work the same, just replace the substring Little
with Big
in the function-names.
Upvotes: 6
Reputation: 48258
the way to do is:
bytearray -> stream ->setorder -> serialize to variable
QByteArray newData = ....;
QDataStream stream(newData);
stream.setByteOrder(QDataStream::LittleEndian); // or BigEndian
stream >> variable;
Upvotes: 4