Add quint16 / unsigned short to QByteArray quickly
In my project, I work with QByteArrays, adding data to them as the program runs. In most cases, a simple one is quint8
added just fine using QByteArray::append()
. But when added quint16
, only 1 byte is added instead of 2.
QByteArray ba = QByteArray::fromHex("010203");
quint number(300);//300 in hex is 012c
ba.append(number);//What should be appended instead of just number?
//the current incorrect result is
ba.toHex() == "0102032c"
//the desired result is
ba.toHex() == "010203012c"
I've already tried this, but it just inserts the value as a string (4 bytes):
ba.append(QByteArray::number(number, 16));
What should I add to the QByteArray so that both "number" bytes are added instead of one byte? In addition, the fastest method is preferred as this program requires excellent runtime. So there is absolutely no conversion to QStrings.
Thank you for your time.
source to share
By itself QByteArray
only supports byte addition; To add an extended representation of fixed-size integer types, you can create your own operator<<
(or whichever you prefer) overloads using the appropriate bit shifts:
QByteArray &operator<<(QByteArray &l, quint8 r)
{
l.append(r);
return l;
}
QByteArray &operator<<(QByteArray &l, quint16 r)
{
return l<<quint8(r>>8)<<quint8(r);
}
QByteArray &operator<<(QByteArray &l, quint32 r)
{
return l<<quint16(r>>16)<<quint16(r);
}
This allows you to write code like:
QByteArray b;
b<<quint16(300); // appends 0x01 0x2c
b<<quint8(4); // appends 0x04
b<<quint16(4); // appends 0x00 0x04
b<<quint32(123456); // appends 0x00 0x01 0xe2 0x40
b<<quint8(1)<<quin16(2)<<quint32(3); // appends 0x01 0x00 0x02 0x00 0x00 0x00 0x03
You should probably avoid writing
QByteArray b;
b<<1;
because in theory the output depends on the size of the current integer platform (although AFAIK on all platforms supported by Qt int
it is 32 bits).
source to share