Skip to content

Instantly share code, notes, and snippets.

@MuntashirAkon
Created January 29, 2022 17:52
Show Gist options
  • Save MuntashirAkon/6eb814fc19f53359aee0e4ef81bd074f to your computer and use it in GitHub Desktop.
Save MuntashirAkon/6eb814fc19f53359aee0e4ef81bd074f to your computer and use it in GitHub Desktop.
Hexify in C/CPP
// Get a byte array as a hexadecimal character string
int hexify(const 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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment