简体   繁体   English

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

[英]Convert (comma separated hex) String to unsigned char array in Arduino

The response payload of my http request looks like this (but can be modified to any string best suitable for the task): 我的http请求的响应有效负载如下所示(但可以将其修改为最适合该任务的任何字符串):

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

How do I turn it into an unsigned char array containing the hex values like this: 如何将其转换为包含如下十六进制值的无符号char数组:

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

Additional information: The length of the payload string is known in advance and always the same. 附加信息:有效负载字符串的长度是预先已知的,并且始终相同。 Some partial solution I found can't be directly applied due to the limitations of the wrapper nature of Arduino for c++. 由于Arduino for c ++的包装性质的限制,我发现无法直接应用某些部分解决方案。 Looking for a simple solution within the Arduino IDE. 在Arduino IDE中寻找简单的解决方案。

Use sscanf("%x", ...) , here an example of just 3 hex numbers: 使用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

If using sscanf() ( #include <stdio.h> ) is within your limitations then you can call with it "%hhx" to extract each individual hex value into an unsigned char like this: 如果使用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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM