src/hexdump.c

Wed, 05 Aug 2009 17:32:05 +0100

author
Philip Pemberton <philpem@philpem.me.uk>
date
Wed, 05 Aug 2009 17:32:05 +0100
changeset 18
fd1c6f6066da
parent 12
96e1df9bd27c
permissions
-rw-r--r--

updated README

philpem@0 1 #include <stdio.h>
philpem@0 2 #include <ctype.h>
philpem@0 3 #include <string.h>
philpem@0 4
philpem@0 5 void hex_dump(void *data, int size)
philpem@0 6 {
philpem@0 7 /* dumps size bytes of *data to stdout. Looks like:
philpem@0 8 * [0000] 75 6E 6B 6E 6F 77 6E 20
philpem@0 9 * 30 FF 00 00 00 00 39 00 unknown 0.....9.
philpem@0 10 * (in a single line of course)
philpem@0 11 */
philpem@0 12
philpem@0 13 unsigned char *p = data;
philpem@12 14 unsigned long addr = 0;
philpem@0 15 unsigned char c;
philpem@0 16 int n;
philpem@0 17 char bytestr[4] = {0};
philpem@0 18 char addrstr[10] = {0};
philpem@0 19 char hexstr[ 16*3 + 5] = {0};
philpem@0 20 char charstr[16*1 + 5] = {0};
philpem@0 21 for(n=1;n<=size;n++) {
philpem@0 22 if (n%16 == 1) {
philpem@0 23 /* store address for this line */
philpem@12 24 snprintf(addrstr, sizeof(addrstr), "%.4lX",
philpem@12 25 addr);
philpem@0 26 }
philpem@0 27
philpem@0 28 c = *p;
philpem@0 29 if (isalnum(c) == 0) {
philpem@0 30 c = '.';
philpem@0 31 }
philpem@0 32
philpem@0 33 /* store hex str (for left side) */
philpem@0 34 snprintf(bytestr, sizeof(bytestr), "%02X ", *p);
philpem@0 35 strncat(hexstr, bytestr, sizeof(hexstr)-strlen(hexstr)-1);
philpem@0 36
philpem@0 37 /* store char str (for right side) */
philpem@0 38 snprintf(bytestr, sizeof(bytestr), "%c", c);
philpem@0 39 strncat(charstr, bytestr, sizeof(charstr)-strlen(charstr)-1);
philpem@0 40
philpem@0 41 if(n%16 == 0) {
philpem@0 42 /* line completed */
philpem@0 43 printf("[%4.4s] %-50.50s %s\n", addrstr, hexstr, charstr);
philpem@0 44 hexstr[0] = 0;
philpem@0 45 charstr[0] = 0;
philpem@0 46 } else if(n%8 == 0) {
philpem@0 47 /* half line: add whitespaces */
philpem@0 48 strncat(hexstr, " ", sizeof(hexstr)-strlen(hexstr)-1);
philpem@0 49 strncat(charstr, " ", sizeof(charstr)-strlen(charstr)-1);
philpem@0 50 }
philpem@0 51 p++; /* next byte */
philpem@12 52 addr++; /* increment address */
philpem@0 53 }
philpem@0 54
philpem@0 55 if (strlen(hexstr) > 0) {
philpem@0 56 /* print rest of buffer if not empty */
philpem@0 57 printf("[%4.4s] %-50.50s %s\n", addrstr, hexstr, charstr);
philpem@0 58 }
philpem@0 59 }
philpem@0 60