将QString转换为十六进制?

3

我有一个QString,其中包含用户输入的数据。

在QString的末尾,我需要添加“Normal” QString的十六进制表示。

例如:

QString Test("ff00112233440a0a");
QString Input("Words");

Test.append(Input);//but here is where Input needs to be the Hex representation of "Words"

//The resulting variable should be
//Test == "ff00112233440a0a576f726473";

我该如何将ASCII(我想是ASCII码)转换为它的十六进制表示?

感谢你的时间。

2个回答

9
你离正确答案很近:

你能具体一点吗? - deGoot
尝试输入QString“Test1”时的输出为“30303035”。 - mrg95
也许你的Qt版本和我的不一样。我使用的是5.2.1版本。 我更新了答案,通过显式地使用 QString::fromLatin1 函数将 QByteArray 显式转换为 QString ,使其变得更加清晰明了。如果有帮助请告诉我。 - deGoot
很抱歉听到这个。这是我测试的代码:QString Test("ff00112233440a0a"); QString Input("Test1"); Test.append(QString::fromLatin1(Input.toLatin1().toHex())); qDebug() << Test;。这是我得到的结果:ff00112233440a0a5465737431。如果你使用的是Qt4,可以尝试使用toAsciifromAscii代替Latin1。 - deGoot
也许我的代码其他地方有错误。让我检查一下。 - mrg95
啊,是的,我弄明白了。我用错误的变量进行了测试。我犯了个错误。再次感谢 :) - mrg95

0

你的问题还有另一个解决方案。

给定一个字符,你可以使用以下简单的函数来计算它的十六进制表示。

// Call this function twice -- once with the first 4 bits and once for the last
// 4 bits of a char to get the hex representation of a char.
char toHex(char c) {
   // Assume that the input is going to be 0-F.
   if ( c <= 9 ) {
      return c + '0';
   } else {
      return c + 'A' - 10;
   }
}

您可以将其用作:

char c;
// ... Assign a value to c

// Get the hex characters for c
char h1 =  toHex(c >> 4);
char h2 = toHex(c & 0xF);

也许你误解了。输入不是从0-F的十六进制数。它只是一个普通的单词...比如“pie”在十六进制中是“706965”。 - mrg95

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接