Skip to content

Instantly share code, notes, and snippets.

@timkuijsten
Last active December 28, 2019 00:14
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 timkuijsten/8142cfc4bc3abca42a6d17056b7198b3 to your computer and use it in GitHub Desktop.
Save timkuijsten/8142cfc4bc3abca42a6d17056b7198b3 to your computer and use it in GitHub Desktop.
binary to hexadecimal
#include <stddef.h>
/*
* Encode binary data into ASCII hexadecimal numbers.
*
* Return the number of hexadecimals written in "out". If "outlen" is at least
* twice as long as "inlen" the result is not truncated.
*/
size_t
bin2hex(char *out, size_t outlen, const unsigned char *in, size_t inlen)
{
static const char hexmap[] = "0123456789abcdef";
size_t i, j;
for (i = 0, j = 0; i < inlen && j + 1 < outlen; i++, j += 2) {
out[j] = hexmap[in[i] & 0xFU];
out[j + 1] = hexmap[in[i] >> 4];
}
return j;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment