0

I'm working on avr microcontroller, and I want to convert a string like "str = 17E388" into an array of char to be as the following: "char arr[3] = {0x17,0xE3,0x88}". any help, please??

I have found the following function. But I don't know how can I call it.

unsigned char *mkBytArray (char *s, int *len) {
unsigned char *ret;

*len = 0;
if (*s == '\0') return NULL;
ret = malloc (strlen (s) / 2);
if (ret == NULL) return NULL;

while (*s != '\0') {
    if (*s > '9')
        ret[*len] = ((tolower(*s) - 'a') + 10) << 4;
    else
        ret[*len] = (*s - '0') << 4;
    s++;
    if (*s > '9')
        ret[*len] |= tolower(*s) - 'a' + 10;
    else
        ret[*len] |= *s - '0';
    s++;
    *len++;
}
return ret;

}

Nana
  • 1
  • 2
  • One possibility, you can use [`strtol`](https://man7.org/linux/man-pages/man3/strtol.3.html) with the base 16 option to convert the string to a number, then use [`memcpy`](https://man7.org/linux/man-pages/man3/memcpy.3.html) to copy that value to `arr`. Be mindful of endianess, what I've suggested may not work off-the-shelf. You could also loop over `str` two characters at a time, converting and storing to `arr`, giving more initial control over the endianess. – yano Jan 27 '22 at 15:42
  • @yano, `memcpy` would produce different results on different machines. For consistent results, you could use shifts and masks. – ikegami Jan 27 '22 at 15:43
  • If the user wants to translate literals rather than at runtime, then placing `, 0x` on the clipboard and typing two digits, then `Ctrl+V`, then two further digits, rinse, repeat, will do the job with a minimum of fuss. – Wtrmute Jan 27 '22 at 16:09
  • I appreciate your help. the str might be too long like str = 17E3883664FDCE0571 and so on.. so I can not use strtol() – Nana Jan 27 '22 at 16:25

0 Answers0