Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 939
JanSLO Avatar asked Jul 23 '16 12:07

JanSLO


2 Answers

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);
like image 139
mandroid Avatar answered Nov 08 '22 07:11

mandroid


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]);
}
like image 28
Ronald Klop Avatar answered Nov 08 '22 09:11

Ronald Klop