Skip to content

Instantly share code, notes, and snippets.

@cellularmitosis
Last active June 11, 2020 18:17
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save cellularmitosis/0d8c0abf7f8aa6a2dff3 to your computer and use it in GitHub Desktop.
Save cellularmitosis/0d8c0abf7f8aa6a2dff3 to your computer and use it in GitHub Desktop.
hexify: a tiny function which converts binary data into hex. styled after snprintf.

Blog 2015/9/26

<- previous | index | next ->

hexify.c: a snprintf-styled function for turning data into hex

I liked this implementation of a hexification algorithm, so I wrapped it up into a function (styled after the snprintf interface).

$ gcc hexify.c 
$ ./a.out 

test 1
buff: , bytes_written: 0

test 2
buff: , bytes_written: 0

test 3
buff: fe, bytes_written: 2

test 4
buff: fefd, bytes_written: 4

test 5
buff: fcfb, bytes_written: 4
// inspired by http://stackoverflow.com/a/12839870/558735
#include <stdio.h>
#include <stdint.h>
int hexify(uint8_t *in, size_t in_size, char *out, size_t out_size)
{
if (in_size == 0 || out_size == 0) return 0;
char map[16+1] = "0123456789abcdef";
int bytes_written = 0;
size_t i = 0;
while(i < in_size && (i*2 + (2+1)) <= out_size)
{
uint8_t high_nibble = (in[i] & 0xF0) >> 4;
*out = map[high_nibble];
out++;
uint8_t low_nibble = in[i] & 0x0F;
*out = map[low_nibble];
out++;
i++;
bytes_written += 2;
}
*out = '\0';
return bytes_written;
}
int main()
{
int testnum = 0;
{
testnum++;
printf("\ntest %i\n", testnum);
uint8_t bytes[1] = {254};
char buff[1];
int bytes_written = hexify(bytes, sizeof(bytes), buff, sizeof(buff));
printf("buff: %s, bytes_written: %i\n", buff, bytes_written);
}
{
testnum++;
printf("\ntest %i\n", testnum);
uint8_t bytes[1] = {254};
char buff[2];
int bytes_written = hexify(bytes, sizeof(bytes), buff, sizeof(buff));
printf("buff: %s, bytes_written: %i\n", buff, bytes_written);
}
{
testnum++;
printf("\ntest %i\n", testnum);
uint8_t bytes[1] = {254};
char buff[2+1];
int bytes_written = hexify(bytes, sizeof(bytes), buff, sizeof(buff));
printf("buff: %s, bytes_written: %i\n", buff, bytes_written);
}
{
testnum++;
printf("\ntest %i\n", testnum);
uint8_t bytes[2] = {254, 253};
char buff[4+1];
int bytes_written = hexify(bytes, sizeof(bytes), buff, sizeof(buff));
printf("buff: %s, bytes_written: %i\n", buff, bytes_written);
}
{
testnum++;
printf("\ntest %i\n", testnum);
uint8_t bytes[3] = {252, 251, 250};
char buff[4+1];
int bytes_written = hexify(bytes, sizeof(bytes), buff, sizeof(buff));
printf("buff: %s, bytes_written: %i\n", buff, bytes_written);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment