QByteArray ba;
QDataStream ds(&ba,QIODevice::WriteOnly);
ds<<quint8(1)<<quint16(2)<<quint32(3); //1+2+4
qDebug()<<"size:"<<ba.size(); // 7
I use QDataStream
to write 3 number, ba.size() is 7, but I'm confused about this:
QByteArray ba;
QDataStream ds(&ba,QIODevice::WriteOnly);
QString s="a";
ds<<quint8(1)<<quint16(2)<<quint32(3)<<s; //1+2+4+a
qDebug()<<"size:"<<ba.size(); // 13
If a QString's size
is 1, ba's size plus 6, why is that? sizeof(QString)
is 4.
Let's analyze the difference between both impressions:
And for that, let's review the source code:
That method uses the
writeBytes()
method, and according to the docs:That is, apart from writing the data, write the length of the text in
quint32
format (4 bytes) and the length of the buffer is equal tosizeOf(QChar)
xlength of the QString
.Taking into account in it we can understand the result better:
In general you can use the following formula to calculate the size of the stored data: