String array which is hex array to byte array

I get string from other device like A1B2C3D4 and I need to convert it to uint8_t, but it have to look like uint8_t hex[] = { 0xA1, 0xB2, 0xC3, 0xD4 };

Any hints?

If its always a string representing 4 bytes, then you could do something like:

union hexdata{
    unsigned long val;
    uint8_t hex[4];
}

char text[] = "A1B2C3D4";
char *ptr;
hexdata.val = strtoul(text, &ptr, 16);

You can then access the data as a 32-bit value via hexdata.val, or the individual bytes with hexdata.hex[0] thru hexdata.hex[3].

If its more than 4 bytes, then the solution by blh4 will work for any number of bytes provided you size uint8_t hex[] accordingly.

use sscanf() using the %2x conversion specification, e.g.

void setup() {
  Serial.begin(115200);
  char text[]="A1B2C3D4";
  int a, b, c, d;
  sscanf(text,"%2x%2x%2x%2x", &a, &b, &c, &d);
  Serial.println(a, HEX);
  Serial.println(b, HEX);
  Serial.println(c, HEX);
  Serial.println(d, HEX);
}

void loop() {}

serial monitor prints

A1
B2
C3
D4
char input[] = "A1B2C3D4";
uint8_t hex[4];

for( int i=0; i < strlen(input); i+=2 ) {
  char c = input[i];
  if ( c >= '0' && c <= '9' ) c -= '0';
  else c -= 'A' + 10;
  hex[i/2] = c * 16;
  c = input[i+1];
  if ( c >= '0' && c <= '9' ) c -= '0';
  else c -= 'A' + 10;
  hex[i/2] += c;
}

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.