hexdump.h (1100B)
1 #ifndef HEXDUMP_H 2 #define HEXDUMP_H 3 4 #ifdef __cplusplus 5 extern "C" { 6 #endif 7 8 #include <stdio.h> 9 10 /* Based on: http://stackoverflow.com/a/7776146 */ 11 static void hexdump(const char *desc, const void *addr, size_t len, FILE *fp) { 12 unsigned int i; 13 unsigned char buf[17]; 14 const unsigned char *pc = (const unsigned char*)addr; 15 16 /* Output description if given. */ 17 if (desc != NULL) fprintf(fp, "%s:\n", desc); 18 19 for (i = 0; i < (unsigned int)len; i++) { 20 21 if ((i % 16) == 0) { 22 if (i != 0) fprintf(fp, " |%s|\n", buf); 23 fprintf(fp, "%08x ", i); 24 } else if ((i % 8) == 0) { 25 fprintf(fp, " "); 26 } 27 fprintf(fp, " %02x", pc[i]); 28 if ((pc[i] < 0x20) || (pc[i] > 0x7e)) { 29 buf[i % 16] = '.'; 30 } else { 31 buf[i % 16] = pc[i]; 32 } 33 buf[(i % 16) + 1] = '\0'; 34 } 35 if (i % 16 <= 8 && i % 16 != 0) fprintf(fp, " "); 36 while ((i % 16) != 0) { 37 fprintf(fp, " "); 38 i++; 39 } 40 fprintf(fp, " |%s|\n", buf); 41 } 42 43 #ifdef __cplusplus 44 } 45 #endif 46 47 #endif /* HEXDUMP_H */