3

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 ?

1

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Don't forget to include #include <QtEndian>
4

the way to do is:

bytearray -> stream ->setorder -> serialize to variable QByteArray newData = ....; QDataStream stream(newData); stream.setByteOrder(QDataStream::LittleEndian); // or BigEndian stream >> variable; 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.