简体   繁体   中英

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?

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.

the way to do is:

bytearray -> stream ->setorder -> serialize to variable


QByteArray newData = ....;
QDataStream stream(newData);
stream.setByteOrder(QDataStream::LittleEndian); // or BigEndian
stream >> variable;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM