Skip to content

Instantly share code, notes, and snippets.

@tolgahanakgun
Forked from ccbrown/DumpHex.c
Last active December 14, 2022 13:12
Show Gist options
  • Save tolgahanakgun/3e492bef9c3eded37807ca92a9b35988 to your computer and use it in GitHub Desktop.
Save tolgahanakgun/3e492bef9c3eded37807ca92a9b35988 to your computer and use it in GitHub Desktop.
Compact C Hex Dump Function w/ASCII to buffer
#include <stdio.h>
void dump_hex(const void *data, size_t size, char *output)
{
char ascii[17];
size_t i, j;
ascii[16] = '\0';
for (i = 0; i < size; ++i)
{
if ((i % 16) == 0)
{
output += sprintf(output, "%08x ", i);
}
output += sprintf(output, "%02X ", ((unsigned char *) data)[i]);
if (((unsigned char *) data)[i] >= ' ' && ((unsigned char *) data)[i] <= '~')
{
ascii[i % 16] = ((unsigned char *) data)[i];
}
else
{
ascii[i % 16] = '.';
}
if ((i + 1) % 8 == 0 || i + 1 == size)
{
output += sprintf(output, "%c", ' ');
if ((i + 1) % 16 == 0)
{
output += sprintf(output, " %s \n", ascii);
}
else if (i + 1 == size)
{
ascii[(i + 1) % 16] = '\0';
if ((i + 1) % 16 <= 8)
{
output += sprintf(output, "%c", ' ');
}
for (j = (i + 1) % 16; j < 16; ++j)
{
output += sprintf(output, "%s", " ");
}
output += sprintf(output, " %s \n", ascii);
}
}
}
*(output) = '\0';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment