Hoehli
Hoehli

Reputation: 164

How to get ASCII characters out of hexadecimal values contained in a QString?

I have a QString containing multipe hexadecimal values from 0x00 to 0xFF. I get the string from a QTableWidget and I want to convert the hex values in it to their corresponding ASCII characters, i.e. 0xAA => ª, 0xFF => ÿ, etc. The result should be displayed in a QTextEdit.

Here is a minimal excample:

#include <QCoreApplication>
#include <QDebug>

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    QString asciiAsQString = "0x4A 0x3B 0x1F 0x0D";
    qDebug() << "hex as qstring." << asciiAsQString;
    QString f;

    for(int i = 0; i < asciiAsQString.length(); i++)
    {
        f.append(QChar(asciiAsQString.at(i).toLatin1()));
    }
    qDebug() << "ascii of hex contained in qString:" << f;
    return a.exec();
}

I have tried this and several similar things, but nothing works as I expect.

How can I fix the code to achieve the desired result?

Upvotes: 1

Views: 1632

Answers (2)

Toby Speight
Toby Speight

Reputation: 30970

You could split on spaces, and convert each substring using QString::toUShort(), like this:

#include <QDebug>

int main()
{
    QString input = "0x61 43 0xaf 0x20 0x2192 32 0xAA";
    qDebug() << "Hex chars:" << input;

    QString output;

    for (auto const& s: input.split(' ', QString::SkipEmptyParts))
    {
        bool ok;
        auto n = s.toUShort(&ok, 0);
        if (!ok) {
            qWarning() << "Conversion failure:" << s;
        } else {
            output.append(QChar{n});
        }
    } 
    qDebug() << "As characters:" << qPrintable(output);
}

Output:

Hex chars: "0x61 43 0xaf 0x20 0x2192 32 0xAA"
As characters: a+¯ → ª

Upvotes: 1

You need something like

    QString asciiAsQString = "0x4A 0x3B 0x1F 0x0D";
    // You may need a bit of error checking to ensure the string is the right
    // format here.
    asciiAsQString.replace("0x", "").replace(" ","");  // Remove '0x' and ' '
    const QByteArray hex = asciiAsQString.toLatin1();
    const QByteArray chars = hex.fromHex();
    const QString text = chars.fromUtf8();

Depending on the encoding that the user is expected to enter, the last line should be .fromLatin1() or .fromLocal8Bit(). I would encourage you to allow Utf8, because it allows the full range of Unicode. It does mean ª would need to be entered as "C2 AA", but 提 can be entered as "E6 8F 90".

Upvotes: 2

Related Questions