【问题标题】:Converting hexadecimal string to char将十六进制字符串转换为字符
【发布时间】:2018-01-26 10:20:26
【问题描述】:

我得到“3838”作为字符串。喜欢:

String example = "3838";

十六进制等于 (88)。 (我在这里转换:http://www.unit-conversion.info/texttools/hexadecimal/

但我需要像这里一样将它用作字符:

char data[] = {0x88,0x0f,0xc7,0xae,0x76,0x85,0xe9,0xb1,0x8f,0x2f,0x2a,0xd3,0x60,0x37,0x6b,0x6d}; 

我该怎么做?抱歉表达不好。非常感谢。

【问题讨论】:

  • 十进制的3838怎么能是十六进制的88
  • 0x38 是 ascii 表中的字符 '8'。不知道这是否是 OP 所要求的......
  • @StephanLechner 我想他是说 0x38 是 '8' 的 ASCII 码,所以“3838”是“88”
  • 您是想将每个字符转换为十六进制值还是将整个字符串转换为一个十六进制值?还是每两个字符?不是很清楚。
  • 另外,从技术上讲,这是 C++,因为 String 是 Arduino 特定的类。

标签: c arduino hex


【解决方案1】:

根据您的 cmets,您似乎想将 16 位整数值(例如 14392)的高字节和低字节解释为 ASCII 字符(例如 '8'+'8')。为此,您不必为了获得 ASCII 字符而将十进制值“转换”为十六进制值。您可以简单地将高位和低位字节解释为(ASCII-)字符;然后 - 如果需要 - 您可以将两个连续的 ASCII 字符解释为表示十六进制值的字符串并将其转换为十进制。 不知道为什么您实际上需要它,但请参阅以下代码。希望对您有所帮助。

#include <iostream>
#include <iomanip>

int main() {

    u_int16_t decVal = 14392;
    cout << "original dec value: " << decVal << endl;
    cout << "dec value as hex: 0x" << std::hex << std::setfill('0') << decVal  << endl;
    char c1 = (decVal&0x7F00 >> 8);
    char c2 = (decVal&0x7F);
    char hexStr[3] = { c1, c2, '\0' };
    cout << "2 bytes interpreted as ASCII: " << hexStr << endl;

    char *lastCharInterpreted;
    decVal = strtol(hexStr, &lastCharInterpreted, 16);
    if (lastCharInterpreted == hexStr) {
        cout << "invalid hexadecimal value: "  << hexStr << endl;
    }
    else {
        cout << "ASCII interpreted as hex and converted to dec:" << std::dec << decVal << endl;
    }

    return 0;
}

输出:

original dec value: 14392
dec value as hex: 0x3838
2 bytes interpreted as ASCII: 88
ASCII interpreted as hex and converted to dec:136

【讨论】:

  • 我认为我们有“3838”作为字符串,因此有 4 个字节(不是两个)。这就是输入。现在我们想要将每 2 个字节的数值作为十六进制(0x38 是字符 '8')。取十六进制字符并再次使它们成为十六进制数字,即得到 0x88,十进制为 136 (10001000)。
  • @NO,这正是我所需要的。我需要十进制 136。
  • @Stephan Lechner 非常感谢。但它实际上并没有解决我的问题。有没有可能按照NO所说的去做?
  • @Atalay K.:从 14392136 真的很令人困惑 :-) 希望代码有所帮助。
  • @Stephan Lechner 你太棒了! :) 非常非常感谢你。我将代码实现到 Arduino 没有任何问题。只有一个问题。此代码无法处理十进制 13872 (实际上是 3630 hexadecimal )值。 c1 和 c2 的值为 0。可能是什么问题?
猜你喜欢
  • 2018-01-31
  • 1970-01-01
  • 2013-02-07
  • 1970-01-01
  • 2014-12-04
  • 1970-01-01
  • 2020-11-07
相关资源
最近更新 更多