Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing integer to QByteArray using only 4 bytes

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.
like image 706
c0dehunter Avatar asked Dec 02 '12 11:12

c0dehunter


2 Answers

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));
like image 114
RA. Avatar answered Oct 09 '22 08:10

RA.


@Primož Kralj did not get around to posting a solution with his second method, so here it is:

int myInt = 0xdeadbeef;
QByteArray qba(reinterpret_cast<const char *>(&myInt), sizeof(int));

qDebug("QByteArray has bytes %s", qPrintable(qba.toHex(' ')));

prints:

QByteArray has bytes ef be ad de

on an x64 machine.

like image 1
dqbydt Avatar answered Oct 09 '22 08:10

dqbydt