Created
November 6, 2013 18:10
-
-
Save xsleonard/7341172 to your computer and use it in GitHub Desktop.
hex string to byte array, C
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
unsigned char* hexstr_to_char(const char* hexstr) | |
{ | |
size_t len = strlen(hexstr); | |
IF_ASSERT(len % 2 != 0) | |
return NULL; | |
size_t final_len = len / 2; | |
unsigned char* chrs = (unsigned char*)malloc((final_len+1) * sizeof(*chrs)); | |
for (size_t i=0, j=0; j<final_len; i+=2, j++) | |
chrs[j] = (hexstr[i] % 32 + 9) % 25 * 16 + (hexstr[i+1] % 32 + 9) % 25; | |
chrs[final_len] = '\0'; | |
return chrs; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@guigarma This is pretty helpful. When checking if the string is valid hex it only checks for capital letters A-F (ASCII 65 - 70). If you use something like
sprintf
to produce the hex string then the output will use lowercase letters and the function doesn't work. I added a small check to fix that.