Storing integer to QByteArray using only 4 bytes

自闭症网瘾萝莉.ら 提交于 2019-12-10 02:28:53

问题


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.

回答1:


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



回答2:


@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.




回答3:


Recently I faced the same problem with a little variation. I had to store a vector of unsigned short into QByteArray. The trick with QDataStream did not work for unknown reason. So, my solution is:

QVector<uint16_t> d={1,2,3,4,5};
QByteArray dd((char*)d.data(),d.size()*sizeof(uint16_t));

The way to get the vector back is:

QVector<uint16_t> D;
for(int i=0; i<dd.size()/sizeof(uint16_t); ++i){
  D.push_back(*(uint16_t*)(dd.data()+i*sizeof(uint16_t)) );
}


来源:https://stackoverflow.com/questions/13668827/storing-integer-to-qbytearray-using-only-4-bytes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!