简体   繁体   中英

Convert hex QString to UTF-8 QString

In my project I need to convert a hex QString ("c2a774657374") into a UTF-8 encoded QString ("§test")

My current function (HexToAscii) does convert the hex to ascii, but does not encode it properly:

void HexToInt(QString num_hex, int &num_int)
{
    uint num_uint;
    bool ok;
    num_uint = num_hex.toUInt(&ok,16);
    num_int = (int)num_uint;
}

void HexToAscii(QString &Input)//Input == "c2a774657374"
{
    int inputInt;
    QString tempInput;
    for(int i=0; i<Input.length()/2; i++)
    {
        HexToInt(Input.mid(i*2, 2), inputInt);
        tempInput.append((unsigned char)inputInt);
    }
    Input = tempInput;//Input == "§test"
}

However, this only converts each byte and doesn't follow UTF-8 encoding. The result of my current function is ("§test") when I want it to be ("§test")

How can I edit my HexToAscii function to convert to a UTF-8 encoded QString?

Thanks for your time.

To get a decoded copy of the hex encoded string, you can use QByteArray::fromHex() static function.

QByteArray hex = QByteArray::fromHex("c2a774657374");
QString str = QString::fromUtf8(hex);

Well, on UTF-8, up to 127 it is single byte. The problem is how QString deals with two byte sequences.

The QString cannot tell what "c2" is and proceed to allocate instead to wait for the next byte.

You can fix this by checking if this hex returned is greater than 127 (7f) and concatenating it with the next Hex before appending to QString.

Try:

#include <QCoreApplication>
#include <iostream>


void HexToInt(QString num_hex, int &num_int)
{
    uint num_uint;
    bool ok;
    num_uint = num_hex.toUInt(&ok,16);
    num_int = (int)num_uint;
}

QString HexToAscii(QString Input)//Input == "c2a774657374"
{
    int inputInt;
    int twobytesequece;
    QString tempInput;
    for(int i=0; i<Input.length()/2; i++)
    {
        HexToInt(Input.mid(i*2, 2), inputInt);
        if (inputInt <= 0x7f) {
            tempInput.append((unsigned char)inputInt);
        } else {
            i++;
            HexToInt(Input.mid(i*2, 2), twobytesequece);
            inputInt = inputInt << 8 | twobytesequece;
            tempInput.append((unsigned char)inputInt);
        }
    }
    return tempInput;
}

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    QString test = "c2a774657374";
    test = HexToAscii(test);

    return a.exec();
}

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