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

开源鸿蒙跨平台开发社区汇聚开发者与厂商,共建“一次开发,多端部署”的开源生态,致力于降低跨端开发门槛,推动万物智联创新。

更多推荐