Skip to content

Instantly share code, notes, and snippets.

@nyux
Created August 16, 2014 17:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nyux/e618a9f7b715df8c8abd to your computer and use it in GitHub Desktop.
Save nyux/e618a9f7b715df8c8abd to your computer and use it in GitHub Desktop.
#include <stdlib.h>
#include <string.h>
char* utility_hex_to_ascii(char *hexstr)
{
size_t hexlen = strlen(hexstr);
/* every two characters in a hex string => one byte of ascii, + '\0' */
size_t ascii_len = hexlen / 2;
char *ascii = malloc(sizeof(char) * ascii_len + 1);
if (ascii != NULL)
{
for (int i = 0; i < ascii_len; i++)
{
for (int j = 4; j >= 0; j -= 4)
{
switch (*hexstr)
{
case '0' ... '9':
ascii[i] |= (*hexstr++ - '0') << j;
break;
case 'a' ... 'f':
ascii[i] |= (*hexstr++ - 'a' + 10) << j;
break;
case 'A' ... 'F':
ascii[i] |= (*hexstr++ - 'A' + 10) << j;
break;
}
}
}
ascii[ascii_len] = '\0';
}
return ascii;
}
#ifdef DEBUG
#include <stdio.h>
int main(void)
{
char *translation = utility_hex_to_ascii("61736466");
if (translation)
{
printf("%s", translation); /* should print asdf */
free(translation);
}
return 0;
}
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment