将十六进制字符串转换为char

时间:2017-08-17 20:41:18

标签: c arduino hex

我得到了#38; 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}; 

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

1 个答案:

答案 0 :(得分:2)

根据您的评论,似乎您希望将16位整数值(例如14392)的高字节和低字节解释为ASCII字符(例如'8' + {{1 }})。要实现这一目标,您无需转换"将十进制值转换为十六进制值,然后获取ASCII字符。你可以简单地解释高位和低位字节为(ASCII-)char;然后 - 如果需要 - 您可以将两个连续的ASCII字符解释为表示十六进制值的字符串并将其转换为十进制。 不知道为什么你真的需要它,但是看到下面的代码就是这样做的。希望它有所帮助。

'8'

输出:

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