简体   繁体   English

如何在 C++ 中将 Big/Little-Endian 字节转换为 Integer 和反之亦然

[英]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:-我将使用 QTcpSocket 以这种格式从服务器接收长度分隔的帧:-

+----------+--------------------------------+
| len: u32 |          frame payload         |
+----------+--------------------------------+

where u32 is in 32 bit unsigned integer encoded in Big-Endian format.其中 u32 为 32 位无符号 integer 以 Big-Endian 格式编码。 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?如何将此char*数组或QByteArray的前 4 个字节转换为 32 位无符号整数?

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?因此,如果我有长度为 20 个字节的消息,我如何将 20 作为 32 位无符号整数写入 QByteArray 或大/小端格式的 char*?

You can use Qt's QtEndian utility functions to accomplish that.您可以使用 Qt 的QtEndian实用程序函数来完成此操作。

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:例如,如果您有一个quint32 (或uint32_t )并希望以 little-endian 格式将该值写入 char 数组的前四个字节:

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 ): ...或者,或者,将 char 数组的前四个字节作为 little-endian quint32 (或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. Big-endian 读/写的工作方式相同,只需将函数名称中的 substring Little替换为Big

the way to do is:这样做的方法是:

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


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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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