Search code examples
c++qtutf-16qstring

Qt Convert UTF16 Hex string to QString


I want to convert a string in hex and utf16 codec to QString for example like what I achieve from this code:

QString str1 = QString::fromWCharArray(L"\x0633\x0644\x0627\x0645"); // what I want

but when I try the following code every thing went wrong what is the correct way for doing this.

QByteArray hex =  QByteArray::fromHex("0633064406270645");
// wrong text in str2 it should be equal to str1
QString str2 = QString::fromUtf16((char16_t*)hex.data()); 

Solution

  • What is wrong with this code?

    QByteArray hex =  QByteArray::fromHex("0633064406270645");
    // wrong text in str2 it should be equal to str1
    QString str2 = QString::fromUtf16((char16_t*)hex.data());
    

    Endian is! This is equivalent of L"\x3306\x4406\x2706\x4506" and not of L"\x0633\x0644\x0627\x0645".

    So to overcome this problem you can add BOM to string

    QByteArray hex =  QByteArray::fromHex("FEFF0633064406270645");
    QString str2 = QString::fromUtf16((char16_t*)hex.data());
    

    Didn't test it but is should resolve problem.

    Alternative solution is to flip order of bytes in sigle UTF-16 character (to change it to little endian).

    QByteArray hex =  QByteArray::fromHex("3306440627064506");
    QString str2 = QString::fromUtf16((char16_t*)hex.data());