Here is some very rough, naive, inefficient, and insecure code that implements unhexlify
. It's main limitation is that it doesn't check that hexstr
contains only hex digits. But this should be enough to get you started.
#include <stdio.h>
#include <string.h>
#include <assert.h>
void unhexlify(const char *hexstr, char *binstr)
{
char *p, *q;
assert(strlen(hexstr) > 0);
assert(strlen(hexstr) % 2 == 0); // even length
for (p=hexstr,q=binstr; *p; p+=2,q++)
sscanf(p, "%2x", q);
*q = '\0';
}
int main()
{
char *s = "abc123d35d";
char buf[100];
unhexlify(s, buf);
printf(buf);
}
Call this unhexlify.c, then running this program:
$ ./unhexlify | hexdump -C
00000000 ab c1 23 d3 5d |..#.]|
EDIT:
A more robust example of Python's unhexlify
is of course to be found in the actual Python source code for the binascii
module which can be viewed here. Look at the to_int()
and binascii_unhexlify()
functions.