Qt从二进制数据流中解析大小不确定的字符串 [英] Qt parse string of undefined size from a binary data stream

查看:456
本文介绍了Qt从二进制数据流中解析大小不确定的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个二进制数据流,其中包含应解释为Qstring的数据.从第三个字节开始.这是在客户端上生成软件包的方式.

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

解码是在另一台机器(服务器)上完成的.我想从QByteArray package获取值"filename.txt"Qstring,而不依赖字符串的大小(因为服务器没有该信息),而是依赖字符串终止符00.如何实现?

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?

推荐答案

您应该将QByteArray包装在

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

或者您可以首先将QString传递给流,而无需处理char数组:

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

请注意,这将以utf16格式编写,表示已启用Unicode

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

序列化格式记录在 http://qt-project上. org/doc/qt-5.0/qtcore/datastreamformat.html

这篇关于Qt从二进制数据流中解析大小不确定的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆