QByteArray到QString [英] QByteArray to QString

查看:336
本文介绍了QByteArray到QString的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到QByteArrayQString的问题.

我正在读取文件并将其信息存储在QByteArray中.该文件采用unicode格式,因此包含以下内容:t\0 e\0 s\0 t\0 \0 \0

I'm reading a file and stores its information in a QByteArray. The file is in unicode, so it contains something like: t\0 e\0 s\0 t\0 \0 \0

我正在尝试将此值与指定的值进行比较,但是它失败了,因为在调试器中,我看到它不是unicode字符串.

I'm trying to compare this value to my specified value, but it fails, because in the debugger I see it's not an unicode string.

代码将解释所有内容:

QByteArray Data; //contains unicode string "t\0 e\0 s\0 t\0 \0 \0"
QString myValue = "test"; //value to compare.
if(Data.contains(myValue))
    //do some stuff.
else
    //do other stuff.

在调试器中,向我显示变量Data的值为"t\0 e\0 s\0 t\0 \0 \0",而myValue的值为"test".我该如何解决?

In the debugger, it shows me that the variable Data has the value "t\0 e\0 s\0 t\0 \0 \0" and myValue has the value "test". How can I fix it?

推荐答案

您可以使用 QTextCodec 将字节数组转换为字符串:

You can use QTextCodec to convert the bytearray to a string:

QString DataAsString = QTextCodec::codecForMib(1015)->toUnicode(Data);

(1015是UTF-16、1014 UTF-16LE,1013 UTF-16BE,106 UTF-8)

(1015 is UTF-16, 1014 UTF-16LE, 1013 UTF-16BE, 106 UTF-8)

从您的示例中我们可以看到字符串"test"在您的编码中被编码为"t\0 e\0 s\0 t\0 \0 \0",即每个ascii字符后跟一个\0字节或resp.每个ascii字符均编码为2个字节.唯一以这种方式编码ascii字母的unicode编码是UTF-16或UCS-2(这是UTF-16的受限版本),因此在您的情况下,需要1015 mib(假设您的本地首字母为与输入的字节数相同.

From your example we can see that the string "test" is encoded as "t\0 e\0 s\0 t\0 \0 \0" in your encoding, i.e. every ascii character is followed by a \0-byte, or resp. every ascii character is encoded as 2 bytes. The only unicode encoding in which ascii letters are encoded in this way, are UTF-16 or UCS-2 (which is a restricted version of UTF-16), so in your case the 1015 mib is needed (assuming your local endianess is the same as the input endianess).

这篇关于QByteArray到QString的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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