简体   繁体   中英

Qt QString to QByteArray and back

I have a problem with tranformation from QString to QByteArray and then back to 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. and then convert them to QByteArray (Utf8) and back to QString. The problem is that the character with value 0 and characters with value larger than 55295 fail to convert back to QString.

If I stay within range 1 to < 55297 this test passes.

The characters from 55296 (0xD800) up to 57343 (0xdfff) are surrogate characters . 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 . 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 .

buffer = buffer.append(str);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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