如何从 QString 中包含的十六进制值中获取 ASCII 字符?
How to get ASCII characters out of hexadecimal values contained in a QString?
我有一个QString,其中包含从0x00
到0xFF
的多个十六进制值。 我从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+¯ → ª
相关文章:
- C++为构建时间获取QDateTime的可靠方法
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 如何使用 < 和 > 命令获取 c++ 中的输入和输出?
- 使用指针从C++中的数组中获取最大值
- 如何获取std::result_of函数的返回类型
- 如何在openssl-ecc中获取十六进制格式的私钥
- 使用Unreal C++获取VR耳机的世界位置/方向
- 获取日期异步信号安全吗?如果在信号处理程序中使用,它会导致死锁吗
- 从C字符串中获取奇怪的字符串长度
- 为什么我的for循环不能正确获取argv
- 从python中调用C++函数并获取返回值
- 如何获取一个数字的前3位
- 获取字符串的长度并将其分配给数组
- 无法获取菜单选择以运行函数.C++
- 数组长度,为什么从命令行获取时不能使用它?
- 有没有办法通过使用十进制 ASCII 代码自动类型扣除来获取字符?
- 如何从 QString 中包含的十六进制值中获取 ASCII 字符?
- 从 yytext 获取 ASCII 值
- C++中的移位密码(如何获取ASCII值和处理数字)
- 从C/C++中的数字中获取ASCII字符