Last active
May 17, 2018 19:24
-
-
Save justinc1/33ffb19861b7ec9296f145883021909a to your computer and use it in GitHub Desktop.
hexdump -C in C
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <string.h> | |
#include <ctype.h> | |
#include <stdbool.h> | |
/* | |
Implement "hexdump -C" utility. | |
*/ | |
void hexdump(void* ptr, size_t size, size_t addr0); | |
#define OUTF stdout | |
void hexdump(void* ptr, size_t size, size_t addr0) { | |
size_t ii, jj; | |
bool first_repeat=false; | |
size_t sz2; | |
unsigned char tmp[16+2]="", curline[16+2], prevline[16+2]="empty"; | |
for (jj=0; jj<(size+15)/16; jj++) { | |
sz2 = 16; | |
if ((jj+1)*16 > size) { | |
sz2 = size - jj*16; | |
} | |
memcpy(tmp, ((char*)ptr) + jj*16, sz2); | |
memcpy(curline, ((char*)ptr) + jj*16, sz2); | |
tmp[sz2]='\0'; | |
curline[sz2]='\0'; | |
if (memcmp(prevline, curline, sz2) == 0) { | |
if (sz2 != 16) { | |
fprintf(OUTF, "%08lx\n", addr0 + jj*16); | |
first_repeat = false; | |
} | |
else { | |
if (first_repeat) { | |
fprintf(OUTF, "*\n"); | |
first_repeat = false; | |
} | |
} | |
continue; | |
} | |
else { | |
first_repeat = true; | |
} | |
fprintf(OUTF, "%08lx ", addr0 + jj*16); | |
for(ii=0; ii<8 && ii<sz2; ii++) { | |
fprintf(OUTF, " %02x", tmp[ii]); | |
} | |
fprintf(OUTF, " "); | |
for(ii=8; ii<16 && ii<sz2; ii++) { | |
fprintf(OUTF, " %02x", tmp[ii]); | |
} | |
for(ii=sz2; ii<16; ii++) { | |
fprintf(OUTF, " "); | |
} | |
for(ii=0; ii<sz2; ii++) { | |
if(tmp[ii] == ' ' || | |
isalnum(tmp[ii]) || | |
isgraph(tmp[ii]) ) | |
continue; | |
tmp[ii] = '.'; | |
} | |
fprintf(OUTF, " |%s|\n", tmp); | |
memcpy(prevline, curline, sz2); | |
} | |
fprintf(OUTF, "%08lx\n", addr0 + size); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment