在Arduino中将(逗号分隔的十六进制)字符串转换为无符号char数组

时间:2018-09-12 13:07:44

标签: c++ arrays arduino nodemcu string-conversion

http请求的响应有效负载如下所示(但可以将其修改为最适合该任务的任何字符串):

"{0X00,0X01,0XC8,0X00,0XC8,0X00,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,}"

如何将其转换为包含如下十六进制值的无符号char数组:

unsigned char gImage_test[14] = { 0X00,0X01,0XC8,0X00,0XC8,0X00,
0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,}

其他信息:有效负载字符串的长度是预先已知的,并且始终相同。由于Arduino for c ++的包装性质的限制,我发现无法直接应用某些部分解决方案。在Arduino IDE中寻找简单的解决方案。

2 个答案:

答案 0 :(得分:0)

使用sscanf("%x", ...),这里仅是3个十六进制数字的示例:

const char *buffer = "{0X00,0X01,0XC8}";
unsigned int data[3];
int read_count = sscanf(buffer, "{%x,%x,%x}", data, data+1, data+2);
// if successful read_count will be 3

答案 1 :(得分:0)

如果在您的限制范围内使用sscanf()#include <stdio.h>),则可以调用"%hhx"将每个十六进制值提取到unsigned char中,如下所示:

const int PAYLOAD_LENGTH = 14; // Known in advance
unsigned char gImage_test[PAYLOAD_LENGTH];

#include <stdio.h>

int main()
{
    const char* bufferPtr = "{0X00,0X01,0XC8,0X00,0XC8,0X00,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF,0XFF}";
    for (int i = 0; i < PAYLOAD_LENGTH && sscanf(bufferPtr + 1, "%hhx", &gImage_test[i]); i++, bufferPtr += 5);

    return 0;
}