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