TheMeaningfulEngineer
TheMeaningfulEngineer

Reputation: 16349

Qt parse string of undefined size from a binary data stream

I have a binary data stream which contains data that should be interpreted as a Qstring. Starting from the third byte. Here is how the package is generated (on a client).

QByteArray package;
package.append( QByteArray::fromHex("0002") );  // First two bytes
package.append( "filename.txt" );               // String of undefined size
package.append( QByteArray::fromHex("00"));     // End of string

The decoding is done on a different machine (server). I would like to get a Qstring of value "filename.txt" from the QByteArray package without relying on the size of the string (since the server doesn't have that information) but on the string terminator 00. How can this be achieved?

Since this decoding will be done on a different machine, how should the raw data be generated on the client to avoid problems with endianess?

Upvotes: 0

Views: 1394

Answers (1)

ratchet freak
ratchet freak

Reputation: 48196

You should wrap the QByteArray in a QDataStream so you can specify the endianess explicitly and make use of the stream operators

QByteArray package;
QDataStream stream(package, QIODevice::WriteOnly);
stream.setByteOrder( QDataStream::BigEndian);
stream << static_cast<quint16>(0x0002);  // First two bytes
stream << "filename.txt";               // String of undefined size
// no need to write terminating 0 because data stream will prepend length

then you can read in the other direction:

QByteArray package;
QDataStream stream(package, QIODevice::WriteOnly);
stream.setByteOrder( QDataStream::BigEndian);
quint16 id;
stream >> id;  // First two bytes
char* filename;
stream >> filename; // String of undefined size
QString file = QString.fromLatin1(filename);
delete[] filename; //cleanup

or you can pass a QString to the stream in the first place and not need to deal with the char array:

QByteArray package;
QDataStream stream(package, QIODevice::WriteOnly);
stream.setByteOrder( QDataStream::BigEndian);
stream << static_cast<quint16>(0x0002);  // First two bytes
stream << QStringLiteral("filename.txt"); // String of undefined size

note that this will write in utf16 meaning it is unicode enabled

the serialization format is documented at http://qt-project.org/doc/qt-5.0/qtcore/datastreamformat.html

Upvotes: 1

Related Questions