Skip to content

Instantly share code, notes, and snippets.

@noam1023
Forked from richinseattle/hexdump.c
Created May 8, 2020 12:25
Show Gist options
  • Save noam1023/22c24b17f8fac97f61e9ea8fa2db5fa6 to your computer and use it in GitHub Desktop.
Save noam1023/22c24b17f8fac97f61e9ea8fa2db5fa6 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <ctype.h>
#ifndef HEXDUMP_COLS
#define HEXDUMP_COLS 16
#endif
void hexdump(void *mem, unsigned int len)
{
unsigned int i, j;
for(i = 0; i < len + ((len % HEXDUMP_COLS) ? (HEXDUMP_COLS - len % HEXDUMP_COLS) : 0); i++)
{
/* print offset */
if(i % HEXDUMP_COLS == 0)
{
printf("0x%06x: ", i);
}
/* print hex data */
if(i < len)
{
printf("%02x ", 0xFF & ((char*)mem)[i]);
}
else /* end of block, just aligning for ASCII dump */
{
printf(" ");
}
/* print ASCII dump */
if(i % HEXDUMP_COLS == (HEXDUMP_COLS - 1))
{
for(j = i - (HEXDUMP_COLS - 1); j <= i; j++)
{
if(j >= len) /* end of block, not really printing */
{
putchar(' ');
}
else if(isprint(((char*)mem)[j])) /* printable char */
{
putchar(0xFF & ((char*)mem)[j]);
}
else /* other char */
{
putchar('.');
}
}
putchar('\n');
}
}
}
#ifdef HEXDUMP_TEST
int main(int argc, char *argv[])
{
hexdump(argv[0], 20);
return 0;
}
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment