简体   繁体   English

Qt QString到QByteArray并返回

[英]Qt QString to QByteArray and back

I have a problem with tranformation from QString to QByteArray and then back to QString: 从QString转换到QByteArray然后回到QString有一个问题:

int main() {

    QString s;

    for(int i = 0; i < 65536; i++) {
        s.append(QChar(i));
    }

    QByteArray ba = s.toUtf8();

    QString s1 = QString::fromUtf8(ba);

    if(areSame(s, s1)) {
        qDebug() << "OK";
    } else {
       qDebug() << "FAIL";
       outputErrors(s, s1);
    }

    return 0;
}

As you can see I fill QString with all characters that are within 16bit range. 如您所见,我使用16位范围内的所有字符填充QString。 and then convert them to QByteArray (Utf8) and back to QString. 然后将它们转换为QByteArray(Utf8)并返回QString。 The problem is that the character with value 0 and characters with value larger than 55295 fail to convert back to QString. 问题是值为0的字符和值大于55295的字符无法转换回QString。

If I stay within range 1 to < 55297 this test passes. 如果我保持在1到<55297的范围内,则该测试通过。

The characters from 55296 (0xD800) up to 57343 (0xdfff) are surrogate characters . 从55296(0xD800)到57343(0xdfff)的字符代理字符 You can see it as an escape character for the character after it. 您可以将其视为后面角色的转义字符。 They have no meaning in itself. 它们本身没有任何意义。

You can check it by running: 您可以通过运行来检查它:

// QChar(0) was omitted so s and s1 start with QChar(1)
for (int i = 1 ; i < 65536 ; i++)
{
    qDebug() << i << QChar(i) << s[i-1]  << s1[i-1] << (s[i-1] == s1[i-1]);
}

I had a task to convert std::string to QString , and QString to QByteArray . 我有一个任务转换std::stringQString ,并QStringQByteArray Following is what I did in order to complete this task. 以下是我为完成此任务所做的工作。

std::string str = "hello world";

QString qstring = QString::fromStdString(str);

QByteArray buffer;

If you look up the documentation for " QByteArray::append ", it takes QString and returns QByteArray . 如果你查找“ QByteArray::append ”的文档,它需要QString并返回QByteArray

buffer = buffer.append(str);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM