src/hexdump.c

Mon, 03 Aug 2009 14:09:20 +0100

author
Philip Pemberton <philpem@philpem.me.uk>
date
Mon, 03 Aug 2009 14:09:20 +0100
changeset 5
1204ebf9340d
parent 0
0eef8cf74b80
child 12
96e1df9bd27c
permissions
-rw-r--r--

added P-touch decoder source

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@0 14 unsigned char c;
philpem@0 15 int n;
philpem@0 16 char bytestr[4] = {0};
philpem@0 17 char addrstr[10] = {0};
philpem@0 18 char hexstr[ 16*3 + 5] = {0};
philpem@0 19 char charstr[16*1 + 5] = {0};
philpem@0 20 for(n=1;n<=size;n++) {
philpem@0 21 if (n%16 == 1) {
philpem@0 22 /* store address for this line */
philpem@0 23 snprintf(addrstr, sizeof(addrstr), "%.4x",
philpem@0 24 ((unsigned int)p-(unsigned int)data) );
philpem@0 25 }
philpem@0 26
philpem@0 27 c = *p;
philpem@0 28 if (isalnum(c) == 0) {
philpem@0 29 c = '.';
philpem@0 30 }
philpem@0 31
philpem@0 32 /* store hex str (for left side) */
philpem@0 33 snprintf(bytestr, sizeof(bytestr), "%02X ", *p);
philpem@0 34 strncat(hexstr, bytestr, sizeof(hexstr)-strlen(hexstr)-1);
philpem@0 35
philpem@0 36 /* store char str (for right side) */
philpem@0 37 snprintf(bytestr, sizeof(bytestr), "%c", c);
philpem@0 38 strncat(charstr, bytestr, sizeof(charstr)-strlen(charstr)-1);
philpem@0 39
philpem@0 40 if(n%16 == 0) {
philpem@0 41 /* line completed */
philpem@0 42 printf("[%4.4s] %-50.50s %s\n", addrstr, hexstr, charstr);
philpem@0 43 hexstr[0] = 0;
philpem@0 44 charstr[0] = 0;
philpem@0 45 } else if(n%8 == 0) {
philpem@0 46 /* half line: add whitespaces */
philpem@0 47 strncat(hexstr, " ", sizeof(hexstr)-strlen(hexstr)-1);
philpem@0 48 strncat(charstr, " ", sizeof(charstr)-strlen(charstr)-1);
philpem@0 49 }
philpem@0 50 p++; /* next byte */
philpem@0 51 }
philpem@0 52
philpem@0 53 if (strlen(hexstr) > 0) {
philpem@0 54 /* print rest of buffer if not empty */
philpem@0 55 printf("[%4.4s] %-50.50s %s\n", addrstr, hexstr, charstr);
philpem@0 56 }
philpem@0 57 }
philpem@0 58