It's fairly easy with a lookup table:
const char * const quads = { "0000", "0001", "0010", .... };
const char * hex_to_bin_quad(unsigned char c)
{
if (c >= '0' && c <= '9') return quads[ c - '0'];
if (c >= 'A' && c <= 'F') return quads[10 + c - 'A'];
if (c >= 'a' && c <= 'f') return quads[10 + c - 'a'];
return -1;
}
Now iterate over your string and append hex_to_bin_quad(c)
for each character (e.g. using strncat
). You already know that you'll need a target string of length 4 * strlen(src) + 1
, so allocate, iterate and concatenate.