Created
September 9, 2019 21:36
-
-
Save gfnord/c1d545ebf32542b897b3030e095c5bff to your computer and use it in GitHub Desktop.
bin to hex function in C
This file contains hidden or 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
void tohex(unsigned char * in, size_t insz, char * out, size_t outsz) | |
{ | |
unsigned char * pin = in; | |
const char * hex = "0123456789ABCDEF"; | |
char * pout = out; | |
for(; pin < in+insz; pout +=2, pin++){ | |
pout[0] = hex[(*pin>>4) & 0xF]; | |
pout[1] = hex[ *pin & 0xF]; | |
if (pout + 2 - out > outsz){ | |
/* Better to truncate output string than overflow buffer */ | |
/* it would be still better to either return a status */ | |
/* or ensure the target buffer is large enough and it never happen */ | |
break; | |
} | |
} | |
pout[-1] = 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment