简体   繁体   中英

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):

"{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:

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++. Looking for a simple solution within the Arduino IDE.

Use sscanf("%x", ...) , here an example of just 3 hex numbers:

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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