3

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!

PythonNoob
  • 914
  • 1
  • 7
  • 15

3 Answers3

1

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.

Stephan Lechner
  • 34,891
  • 4
  • 35
  • 58
1

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]

PythonNoob
  • 914
  • 1
  • 7
  • 15
  • 1
    The syntax in CAPL for strtol is: int strtol(char s[], dword startIndex, long& result); or int strtol(char s[], long& result); – PythonNoob Nov 15 '18 at 18:39
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("");
}
Toby Speight
  • 27,591
  • 48
  • 66
  • 103
  • 1
    `sscanf(input, "%hhi, %n", b, &position) == 1; ... input += position;` is dangerous as it is not certain `position` has been set. It is not known scanning went past the `','`. The last `input += position;` will be UB. – chux - Reinstate Monica Nov 15 '18 at 18:14
  • Yes, good point. On most platforms, it's safe to perform the addition if you don't dereference it, but that's not a portable assumption, so it should be fixed (e.g. by scanning the `,` into a dummy `char`, and testing for the return being 2 rather than 1). – Toby Speight Nov 15 '18 at 18:26