您应该将QByteArray
a包装起来,QDataStream
以便您可以明确指定字节顺序并使用流运算符
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
然后你可以从另一个方向阅读:
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
或者您可以首先将 QString 传递给流,而无需处理 char 数组:
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
请注意,这将用 utf16 写入,这意味着它启用了 unicode
序列化格式记录在http://qt-project.org/doc/qt-5.0/qtcore/datastreamformat.html