Hex String to Byte Array

Hello,

I’m having trouble figuring out how to convert a hex string such as “A489B1” into an array like [0xA4, 0x89, 0xB1].

Anyone have any ideas?

Thank you!

Use strtoul. Then use a cast or a union to see the unsigned long as an array of four bytes.

you could try something like this

char buf[40];

void setup() {
 Serial.begin (115200);
}

void loop() {
 convert("ab4567");
 Serial.println(buf);
 
}

void convert(char *s)
{
 int i, j, k;
 buf[0] = 0x0;
 
 for (j = 0, i = 0, k = 0; j < strlen(s); j++)
 {
   
   if (i++ == 0) {
     buf[k++] = '0';
     buf[k++] = 'x';
   }
   
   buf[k++] = s[j];
   
   if (i == 2) {
     if(j != strlen(s) -1)  buf[k++] = ',';
     i = 0;
   }
 }

buf[k] = 0x0;

}
// convert a hex string such as "A489B1" into an array like [0xA4, 0x89, 0xB1].

const byte MaxByteArraySize = 5;

void setup()
{
  Serial.begin(115200);

  byte byteArray[MaxByteArraySize] = {0};

  hexCharacterStringToBytes(byteArray, "A489B1");
  dumpByteArray(byteArray, MaxByteArraySize);

  hexCharacterStringToBytes(byteArray, "A489B10");
  dumpByteArray(byteArray, MaxByteArraySize);
}


void hexCharacterStringToBytes(byte *byteArray, const char *hexString)
{
  bool oddLength = strlen(hexString) & 1;

  byte currentByte = 0;
  byte byteIndex = 0;

  for (byte charIndex = 0; charIndex < strlen(hexString); charIndex++)
  {
    bool oddCharIndex = charIndex & 1;

    if (oddLength)
    {
      // If the length is odd
      if (oddCharIndex)
      {
        // odd characters go in high nibble
        currentByte = nibble(hexString[charIndex]) << 4;
      }
      else
      {
        // Even characters go into low nibble
        currentByte |= nibble(hexString[charIndex]);
        byteArray[byteIndex++] = currentByte;
        currentByte = 0;
      }
    }
    else
    {
      // If the length is even
      if (!oddCharIndex)
      {
        // Odd characters go into the high nibble
        currentByte = nibble(hexString[charIndex]) << 4;
      }
      else
      {
        // Odd characters go into low nibble
        currentByte |= nibble(hexString[charIndex]);
        byteArray[byteIndex++] = currentByte;
        currentByte = 0;
      }
    }
  }
}

void dumpByteArray(const byte * byteArray, const byte arraySize)
{

for (int i = 0; i < arraySize; i++)
{
  Serial.print("0x");
  if (byteArray[i] < 0x10)
    Serial.print("0");
  Serial.print(byteArray[i], HEX);
  Serial.print(", ");
}
Serial.println();
}

byte nibble(char c)
{
  if (c >= '0' && c <= '9')
    return c - '0';

  if (c >= 'a' && c <= 'f')
    return c - 'a' + 10;

  if (c >= 'A' && c <= 'F')
    return c - 'A' + 10;

  return 0;  // Not a valid hexadecimal character
}

void loop() {}

Thank you John, that's great!