Created
August 16, 2014 17:17
-
-
Save nyux/e618a9f7b715df8c8abd to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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