简体   繁体   English

将十六进制QString转换为UTF-8 QString

[英]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") 在我的项目中,我需要将十六进制的QString(“ c2a774657374”)转换为UTF-8编码的QString(“§test”)

My current function (HexToAscii) does convert the hex to ascii, but does not encode it properly: 我当前的函数(HexToAscii)确实将十六进制转换为ascii,但未正确编码:

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. 但是,这仅转换每个字节,并且不遵循UTF-8编码。 The result of my current function is ("§test") when I want it to be ("§test") 当我希望当前函数的结果为(“ test”)时,结果为(“ test”)

How can I edit my HexToAscii function to convert to a UTF-8 encoded QString? 如何编辑HexToAscii函数以转换为UTF-8编码的QString?

Thanks for your time. 谢谢你的时间。

To get a decoded copy of the hex encoded string, you can use QByteArray::fromHex() static function. 要获取十六进制编码字符串的解码副本,可以使用QByteArray :: fromHex()静态函数。

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

Well, on UTF-8, up to 127 it is single byte. 好吧,在UTF-8上,最多127个字节是单字节。 The problem is how QString deals with two byte sequences. 问题是QString如何处理两个字节序列。

The QString cannot tell what "c2" is and proceed to allocate instead to wait for the next byte. QString无法分辨出“ c2”是什么,而是继续分配以等待下一个字节。

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. 您可以通过以下方法解决此问题:检查返回的十六进制是否大于127(7f),然后在附加到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();
}

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

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