Search code examples
cstringuint8t

Programmatically populate a uint8_t array


I have a uint8_t array which should look like this .

uint8_t code[1000] = {0x66, 0xba, 0xf8, 0x03}

Now I cant hard code values in that array instead , I need to insert them one by one from char buffer[300]. The content of char buffer[300] is a space delimited string of hex values "66 ba f8 03"

The code I wrote is -

        char* token = strtok(buffer, " "); 
        // Keep printing tokens while one of the 
        // delimiters present in str[].
        int pc = 0; 
        while (token != NULL) {
            code[pc] = token; // This part is wrong. I need to cast it properly
            token = strtok(NULL, " "); 
            pc++;
        }

How can I convert a string value into a uint8_t value?


Solution

  • Example code that uses strtol to convert hex number strings.

    #include <stdio.h>
    #include <stdlib.h>
    #include <stdint.h>
    #include <string.h>
    
    int main(void)
    {
        char buffer[300] = "66 ba f8 03";
    
        uint8_t code[1000];
    
        long val;
        char *endptr;
    
        char* token = strtok(buffer, " "); 
        // Keep printing tokens while one of the 
        // delimiters present in str[].
        int pc = 0; 
        while (token != NULL) {
    
            /* convert as a base16 number */
            val = strtol(token, &endptr, 16);
    
            /* The character following the number should be the end of the string as the input string is already tokenized. */
            if(*endptr) {
                /* error handling */
            } else if(val < 0) {
                /* error handling */
            } else if(val > UINT8_MAX) {
                /* error handling */
            } else {
                /* The checks above make sure that the value fits into uint8_t. */
                code[pc] = (uint8_t)val;
            }
    
            token = strtok(NULL, " "); 
            pc++;
        }
    
        for(int i = 0; i < pc; i++) {
            printf("code[%d] = 0x%02x\n", i, code[i]);
        }
    
        return 0;
    }
    

    The error handling depends on the rest of your program.

    Notes:

    strtok modifies the input string, so it must not be a const char[] or a string literal.

    The loop doesn't contain a check to out-of-range access to code[pc].

    Edit in the code above: A check for space in *endptr is unnecessary as space is used as the token delimiter, so we should never find a space in the result of strtok.