【问题标题】:Convert QString to Hex?将 QString 转换为十六进制?
【发布时间】:2014-05-08 17:01:37
【问题描述】:

我有一个 QString,我在其中附加来自用户的数据输入。

在 QString 的末尾,我需要附加一个“普通”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(我认为)转换为十六进制表示?

感谢您的宝贵时间。

【问题讨论】:

    标签: c++ qt hex ascii qstring


    【解决方案1】:

    你们很亲密:

    Test.append(QString::fromLatin1(Input.toLatin1().toHex()));

    【讨论】:

    • 你能说得更具体点吗?
    • 尝试输入 QString "Test1" 时的输出是 "30303035"
    • 也许你的 Qt 版本与我的不同。我正在使用 5.2.1。我通过使用QString::fromLatin1 函数将QByteArray 显式转换为QString,更新了答案,使其不那么模糊。让我知道这是否有帮助。
    • 很抱歉听到这个消息。这是我测试的内容:QString Test("ff00112233440a0a"); QString Input("Test1"); Test.append(QString::fromLatin1(Input.toLatin1().toHex())); qDebug() << Test;。这就是我得到的:ff00112233440a0a5465737431。如果您使用的是 Qt4,您可以尝试使用 toAsciifromAscii 而不是 Latin1。
    • 也许我在其他地方的代码中有错误。让我检查一下
    【解决方案2】:

    您的问题的另一种解决方案。

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

    // 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。这只是一个普通的词......就像“派”在十六进制中是“706965”
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-02-24
    • 1970-01-01
    • 1970-01-01
    • 2011-07-28
    • 1970-01-01
    相关资源
    最近更新 更多