Skip to content

Instantly share code, notes, and snippets.

@rene-d
Last active September 16, 2022 04:26
Show Gist options
  • Save rene-d/2a08f37701990a00b3ffa6839b1d1f62 to your computer and use it in GitHub Desktop.
Save rene-d/2a08f37701990a00b3ffa6839b1d1f62 to your computer and use it in GitHub Desktop.
ultra fast dump function in C (output like hexdump -C)
// ultra fast dump function (output like hexdump -C)
void hexdump(const void *data, size_t size)
{
static const char digits[] = "0123456789abcdef";
char line[80]; // we use 79 chars at most
size_t i;
int j;
for (i = 0; i < size; i += 16)
{
// offset in hex (8 digits)
line[0] = digits[(i >> 28) & 0x0f];
line[1] = digits[(i >> 24) & 0x0f];
line[2] = digits[(i >> 20) & 0x0f];
line[3] = digits[(i >> 16) & 0x0f];
line[4] = digits[(i >> 12) & 0x0f];
line[5] = digits[(i >> 8) & 0x0f];
line[6] = digits[(i >> 4) & 0x0f];
line[7] = digits[i & 0x0f];
// placeholder for hex dump
memset(line + 8, ' ', 52);
for (j = 0; (j < 16) && (i + j < size); j += 1)
{
uint8_t byte = ((const uint8_t *)data)[i + j];
// byte as hex digits
size_t o = j * 3 + ((j >= 8) ? 11 : 10);
line[o] = digits[(byte >> 4) & 0xf];
line[o + 1] = digits[byte & 0xf];
// byte as printable char
line[61 + j] = ((byte >= 32) && (byte <= 126)) ? (char)byte : '.';
}
line[60] = '|'; // opening delimiter for ascii dump
line[61 + j] = '|'; // closing delimiter
line[62 + j] = '\n'; // newline
fwrite(line, 1, 63 + j, stdout);
}
printf("%08zx\n", size);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment