如何从 QString 中包含的十六进制值中获取 ASCII 字符?

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

本文关键字:获取 ASCII 字符 十六进制 QString 包含      更新时间:2023-10-16

我有一个QString,其中包含从0x000xFF的多个十六进制值。 我从QTableWidget获取字符串,我想将其中的十六进制值转换为它们相应的 ASCII 字符,即0xAA=>ª0xFF=>ÿ等结果应显示在QTextEdit中。

这是一个最小的示例:

#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();
}

我已经尝试过这个和几个类似的东西,但没有像我期望的那样工作。

如何修复代码以达到预期结果?

你需要类似的东西

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();

根据用户应输入的编码,最后一行应为.fromLatin1().fromLocal8Bit()。 我鼓励你允许Utf8,因为它允许全范围的Unicode。 这确实意味着 ª 需要输入为"C2 AA",但提可以输入为"E6 8F 90"。

您可以拆分空格,并使用QString::toUShort()转换每个子字符串,如下所示:

#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);
}

输出:

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