Skip to content

Instantly share code, notes, and snippets.

@gfnord
Created September 9, 2019 21:36
Show Gist options
  • Save gfnord/c1d545ebf32542b897b3030e095c5bff to your computer and use it in GitHub Desktop.
Save gfnord/c1d545ebf32542b897b3030e095c5bff to your computer and use it in GitHub Desktop.
bin to hex function in C
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