Storing integer to QByteArray using only 4 bytes

c0dehunter picture c0dehunter · Dec 2, 2012 · Viewed 14.7k times · Source

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.

Answer

RA. picture RA. · Dec 2, 2012

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 <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));