It can be very handy, in your C programs, to be able to print raw data in a UNIX xxd fashion. Here is a short function to do that :
hexdump.c :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 | #include <stdio.h> #include <ctype.h> #ifndef HEXDUMP_COLS #define HEXDUMP_COLS 8 #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 |
hexdump.h
1 2 3 4 5 6 | #ifndef _HEXDUMP_H #define _HEXDUMP_H void hexdump(void *mem, unsigned int len); #endif |
It can be tested as a standalone program (which dumps 20 bytes of memory strating at *argv) :
cc --ansi -DHEXDUMP_TEST -o hexdump hexdump.c ./hexdump 0x000000: 2e 2f 68 65 78 64 75 6d ./hexdum 0x000008: 70 00 53 53 48 5f 41 47 p.SSH_AG 0x000010: 45 4e 54 5f ENT_