Search code examples
c++qtendianness

How to Convert Big/Little-Endian bytes to Integer and vice versa in C++


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 ?


Solution

  • the way to do is:

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