Jafuentes
Jafuentes

Reputation: 365

Qt: Convert QString to Hexadecimal

I know this is a very basic question but I'm newbie in Qt and I don't know to do it. I'm trying to convert a QString value (like "AA110011") to hexadecimal. I would like to obtain 0xaa110011. I've tried with this code:

QByteArray b = aString.toUtf8();

for (int i = 0; i < b.length(); i++ )
{
    if ( b[i] >= 65 && b[i] <= 70 )
    {
        b[i] = b[i] - 55;
    }
    else if (b[i] >= 48 && b[i] <= 57)
    {
        b[i] = b[i] - 48;
    }
}

I obtain in the Memory at Vairable "[0]" the value 0a 0a 01 01 00 00 01 01 and I don't know how could I obtain aa 11 00 11.

Could you help me? thanks.

Upvotes: 8

Views: 57299

Answers (4)

Jimit Rupani
Jimit Rupani

Reputation: 510

 QString prgName = query.value(1).toString();
 prgName.toLatin1().toHex();

Upvotes: 3

sfzhang
sfzhang

Reputation: 791

Use QByteArray::fromHex()

QByteArray a = QByteArray::fromHex(s.toLatin1())
qDebug() << a;

Upvotes: 3

Sanyam Goel
Sanyam Goel

Reputation: 2180

Once you have a QString you can do the following

QString res = string.toAscii().toHex();
qDebug() << res;

reference

Upvotes: 4

Frank Osterfeld
Frank Osterfeld

Reputation: 25155

Try QString::toInt, QString::toUInt, QString::toLong etc., for example:

const QString str = QLatin1String("AA110011");
bool ok;
const unsigned int parsedValue = str.toUInt(&ok, 16);
if (!ok) {
    //Parsing failed, handle error here
}

qDebug() << parsedValue;

The second argument is the base, 16 in this case for hexadecimal.

This solution will work if your string fits into a unsigned long long or shorter - it will not work if you want to convert arbitrarily long strings that way.

Upvotes: 10

Related Questions