How to convert hex string to byte array in CAPL?

Viewed 9522

Considering having, for example, this type of hex string:

char hex_str[100] = "0x01 0x03 0x04 0x0A";

How to get out of this string the byte array representation in CAPL, like:

byte hex_str_as_byte_arr[4] = {0x01, 0x03, 0x04, 0x0A};

EDIT: Only Vector CANoe supported data types/functions are allowed!

3 Answers

Use strtok to split the character array into separate hex strings, then use long strtol( const char *restrict str, char **restrict str_end, int base ) to convert each hex string to an integral value.

Thanks to all... Actually I've found a solution myself:

  char hex_str[100] = "0x01 0x03 0x04 0x0A";
  long data[4];
  dword pos = 0;

  pos = strtol(hex_str, pos, data[0]);
  pos = strtol(hex_str, pos, data[1]);
  pos = strtol(hex_str, pos, data[2]);
  pos = strtol(hex_str, pos, data[3]);

  write("0x%02x,0x%02x,0x%02x, 0x%02x", data[0], data[1], data[2], data[3]);

Now it's a simple cast: (byte) data[0]

We can use sscanf() to convert the numbers to unsigned char. In a loop, we'll need to also use a %n conversion to determine the reading position for the next iteration.

Here's a simple example (in real life, you'll need some range checking to make sure you don't overrun the output buffer):

#include <stdio.h>

int main(void)
{
    const char hex_str[100] = "0x01, 0x03, 0x04, 0x0A";
    unsigned char bytes[4];

    {
        int position;
        unsigned char *b = bytes;

        for (const char *input = hex_str;  sscanf(input, "%hhi, %n", b, &position) == 1;  ++b) {
            input += position;
        }
    }

    /* prove we did it */
    for (size_t i = 0;  i < sizeof bytes;  ++i) {
        printf("%hhu ", bytes[i]);
    }
    puts("");
}
Related