Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append a QByteArray to QDataStream?

I have to populate a QByteArray with different data. So I'm using the QDataStream.

QByteArray buffer;
QDataStream stream(&buffer, QIODevice::WriteOnly);

qint8 dataHex= 0x04;
qint8 dataChar = 'V';

stream << dataHex<< dataChar;
qDebug() << buffer.toHex();  // "0456"  This is what I want

However, I would also like to append a QByteArray to the buffer.

QByteArray buffer;
QDataStream stream(&buffer, QIODevice::WriteOnly);

qint8 dataHex= 0x04;
qint8 dataChar = 'V';
QByteArray moreData = QByteArray::fromHex("ff");

stream << dataHex<< dataChar << moreData.data(); // char * QByteArray::data ()
qDebug() << buffer.toHex();  // "045600000002ff00"  I would like "0456ff"

What am I missing?

like image 899
TheMeaningfulEngineer Avatar asked Dec 01 '22 16:12

TheMeaningfulEngineer


1 Answers

when a char* is appended it assumes \0 termination and serializes with writeBytes which also writes out the size first (as uint32)

writeBytes' doc:

Writes the length specifier len and the buffer s to the stream and returns a reference to the stream.

The len is serialized as a quint32, followed by len bytes from s. Note that the data is not encoded.

you can use writeRawData to circumvent it:

stream << dataHex<< dataChar;
stream.writeRawData(moreData.data(), moreDate.size());
like image 66
ratchet freak Avatar answered Dec 23 '22 08:12

ratchet freak