0

I have a char array that contains hex data as ascii text and need to convert it into bytes.

Example

char tagData[8] = {'0', '1', 'A', 'A', 'B', 'B', 'C', 'C' };
uint8_t data[4];

// I need to take the tagData and make it so that data[] contains the following
data[0] = 0x01;
data[1] = 0xAA;
data[2] = 0xBB;
data[3] = 0xCC;`

I have google for how to do this but have not been successful. Thanks for any help you might be able to offer.

Nate
  • 37
  • 1
  • 4
  • On a completely different note, are you asking how to convert chars into their corresponding hex? – LLSv2.0 Mar 11 '20 at 19:45
  • heck. slipped up. thank you for the correction – LLSv2.0 Mar 11 '20 at 19:46
  • 1
    Does this answer your question? [Convert hex string (char \[\]) to int?](https://stackoverflow.com/questions/10156409/convert-hex-string-char-to-int) – LLSv2.0 Mar 11 '20 at 19:47
  • 3
    Does this answer your question? [Converting a hex string to a byte array](https://stackoverflow.com/questions/17261798/converting-a-hex-string-to-a-byte-array) – miszcz2137 Mar 11 '20 at 19:48
  • Thank you for the responses everyone! I cannot upvote the answers yet because rep is too low. – Nate Mar 11 '20 at 20:03

1 Answers1

1

Hex digits are very easy to decode manually, eg:

char tagData[8] = {'0', '1', 'A', 'A', 'B', 'B', 'C', 'C' };
uint8_t data[4];

for(int i = 0, j = 0; i < 8; i += 2, ++j)
{
    uint8_t b;

    char ch = tagData[i];
    if (ch >= '0' && ch <= '9')
        b = ch - '0';
    else if (ch >= 'a' && ch <= 'f')
        b = 10 + (ch - 'a');
    else if (ch >= 'A' && ch <= 'F')
        b = 10 + (ch - 'A');
    else
        // malformed!

    b <<= 4;

    ch = tagData[i+1];
    if (ch >= '0' && ch <= '9')
        b |= ch - '0';
    else if (ch >= 'a' && ch <= 'f')
        b |= 10 + (ch - 'a');
    else if (ch >= 'A' && ch <= 'F')
        b |= 10 + (ch - 'A');
    else
        // malformed!

    data[j] = b;
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770