[Qt-interest] Adding quint32 to a QByteArray
Stephen Bryant
steve at bawue.de
Wed Sep 8 09:54:12 CEST 2010
Hi,
On 07/09/2010 20:24, Francisco Gonzalez wrote:
> Hello,
> Afaik QByteArray class have not a function to add a quint32 data
> directly at some position, (nor any other integer, float or doble types)
> in a platform independent manner.
> Instead it is possible to do:
>
> quint32 number = anyNumber;
> qint64 position = anyPositionNumber;
> QByteArray array;
> QDataStream stream(QByteArray& array, QIODevice::ReadWrite);
> stream.setByteOrder(QDataStream::LittleEndian); // The endian type you want
> stream.device()->seek(position);
> stream << number;
>
> Is there any other option to get this directly to a QByteArray in a
> platform independent way?
There is a quite simple way. You have to ensure the byte array has a
suitable size yourself though, but you can overwrite data in the middle.
#include <QtEndian>
quint32 number = anyNumber;
qint64 position = anyPositionNumber;
QByteArray array;
array.resize( anyPositionNumber + sizeof number );
qToLittleEndian<quint32>( anyNumber, array.data() + anyPositionNumber );
There is also qToBigEndian<>() and qFrom...
Be aware: you've used a qint64 for the position, but a QByteArray is
limited to 2GB. It uses a signed (!) int (normally 32 bits) for its
size type.
Steve
More information about the Qt-interest-old
mailing list