仅使用4个字节将整数存储到QByteArray [英] Storing integer to QByteArray using only 4 bytes
问题描述
表示整数需要4个字节。如何在 QByteArray
中存储 int
,这样它只需要4个字节?
It takes 4 bytes to represent an integer. How can I store an int
in a QByteArray
so that it only takes 4 bytes?
-
QByteArray :: number(..)
将整数转换为字符串,因此占用的字节数超过4个字节。 / li>
-
QByteArray((const char *)& myInteger,sizeof(int))
似乎也不起作用。
QByteArray::number(..)
converts the integer to string thus taking up more than 4 bytes.QByteArray((const char*)&myInteger,sizeof(int))
also doesn't seem to work.
推荐答案
有几种方法可以将整数放入 QByteArray
,但以下通常是最干净的:
There are several ways to place an integer into a QByteArray
, but the following is usually the cleanest:
QByteArray byteArray;
QDataStream stream(&byteArray, QIODevice::WriteOnly);
stream << myInteger;
这样做的好处是允许你将几个整数(或其他数据类型)写入字节数组相当方便。它还允许您使用 QDataStream :: setByteOrder
设置数据的字节顺序。
This has the advantage of allowing you to write several integers (or other data types) to the byte array fairly conveniently. It also allows you to set the endianness of the data using QDataStream::setByteOrder
.
虽然上面的解决方案可行,但 QDataStream
用于存储整数的方法可以在Qt的未来版本中更改。确保它始终有效的最简单方法是显式设置 QDataStream
使用的数据格式的版本:
While the solution above will work, the method used by QDataStream
to store integers can change in future versions of Qt. The simplest way to ensure that it always works is to explicitly set the version of the data format used by QDataStream
:
QDataStream stream(&byteArray, QIODevice::WriteOnly);
stream.setVersion(QDataStream::Qt_5_10); // Or use earlier version
或者,您可以避免使用 QDataStream
完全使用 QBuffer
:
Alternately, you can avoid using QDataStream
altogether and use a QBuffer
:
#include <QBuffer>
#include <QByteArray>
#include <QtEndian>
...
QByteArray byteArray;
QBuffer buffer(&byteArray);
buffer.open(QIODevice::WriteOnly);
myInteger = qToBigEndian(myInteger); // Or qToLittleEndian, if necessary.
buffer.write((char*)&myInteger, sizeof(qint32));
这篇关于仅使用4个字节将整数存储到QByteArray的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!