C++ Qt:将 QString 转换为十六进制
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17653143/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Qt: Convert QString to Hexadecimal
提问by Jafuentes
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:
我知道这是一个非常基本的问题,但我是 Qt 的新手,我不知道该怎么做。我正在尝试将 QString 值(如“AA110011”)转换为十六进制。我想获得 0xaa110011。我试过这个代码:
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.
我在内存变量“[0]”中获得了值 0a 0a 01 01 00 00 01 01,但我不知道如何获得 aa 11 00 11。
Could you help me? thanks.
你可以帮帮我吗?谢谢。
回答by Frank Osterfeld
Try QString::toInt, QString::toUInt, QString::toLongetc., for example:
尝试的QString :: toInt,QString的:: toUInt,QString的:: toLong等,例如:
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.
第二个参数是基数,在这种情况下是十六进制的 16。
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.
如果您的字符串适合 unsigned long long 或更短的字符串,则此解决方案将起作用 - 如果您想以这种方式转换任意长的字符串,则该解决方案将不起作用。
回答by Jimit Rupani
Just use this and thank me later.
只需使用它,稍后再感谢我。
QString prgName = query.value(1).toString();
prgName.toLatin1().toHex();