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(..) converts the integer to string thus taking up more than 4 bytes.

QByteArray((const char*)&myInteger,sizeof(int)) also doesn't seem to work.

解决方案

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;

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.

Update

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

Alternately, you can avoid using QDataStream altogether and use a QBuffer:

#include

#include

#include

...

QByteArray byteArray;

QBuffer buffer(&byteArray);

buffer.open(QIODevice::WriteOnly);

myInteger = qToBigEndian(myInteger); // Or qToLittleEndian, if necessary.

buffer.write((char*)&myInteger, sizeof(qint32));

Logo

DAMO开发者矩阵,由阿里巴巴达摩院和中国互联网协会联合发起,致力于探讨最前沿的技术趋势与应用成果,搭建高质量的交流与分享平台,推动技术创新与产业应用链接,围绕“人工智能与新型计算”构建开放共享的开发者生态。

更多推荐