src/hexdump.c

changeset 0
0eef8cf74b80
child 12
96e1df9bd27c
     1.1 diff -r 000000000000 -r 0eef8cf74b80 src/hexdump.c
     1.2 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.3 +++ b/src/hexdump.c	Wed Apr 01 22:11:05 2009 +0100
     1.4 @@ -0,0 +1,58 @@
     1.5 +#include <stdio.h>
     1.6 +#include <ctype.h>
     1.7 +#include <string.h>
     1.8 +
     1.9 +void hex_dump(void *data, int size)
    1.10 +{
    1.11 +    /* dumps size bytes of *data to stdout. Looks like:
    1.12 +     * [0000] 75 6E 6B 6E 6F 77 6E 20
    1.13 +     *                  30 FF 00 00 00 00 39 00 unknown 0.....9.
    1.14 +     * (in a single line of course)
    1.15 +     */
    1.16 +
    1.17 +    unsigned char *p = data;
    1.18 +    unsigned char c;
    1.19 +    int n;
    1.20 +    char bytestr[4] = {0};
    1.21 +    char addrstr[10] = {0};
    1.22 +    char hexstr[ 16*3 + 5] = {0};
    1.23 +    char charstr[16*1 + 5] = {0};
    1.24 +    for(n=1;n<=size;n++) {
    1.25 +        if (n%16 == 1) {
    1.26 +            /* store address for this line */
    1.27 +            snprintf(addrstr, sizeof(addrstr), "%.4x",
    1.28 +               ((unsigned int)p-(unsigned int)data) );
    1.29 +        }
    1.30 +            
    1.31 +        c = *p;
    1.32 +        if (isalnum(c) == 0) {
    1.33 +            c = '.';
    1.34 +        }
    1.35 +
    1.36 +        /* store hex str (for left side) */
    1.37 +        snprintf(bytestr, sizeof(bytestr), "%02X ", *p);
    1.38 +        strncat(hexstr, bytestr, sizeof(hexstr)-strlen(hexstr)-1);
    1.39 +
    1.40 +        /* store char str (for right side) */
    1.41 +        snprintf(bytestr, sizeof(bytestr), "%c", c);
    1.42 +        strncat(charstr, bytestr, sizeof(charstr)-strlen(charstr)-1);
    1.43 +
    1.44 +        if(n%16 == 0) { 
    1.45 +            /* line completed */
    1.46 +            printf("[%4.4s]   %-50.50s  %s\n", addrstr, hexstr, charstr);
    1.47 +            hexstr[0] = 0;
    1.48 +            charstr[0] = 0;
    1.49 +        } else if(n%8 == 0) {
    1.50 +            /* half line: add whitespaces */
    1.51 +            strncat(hexstr, "  ", sizeof(hexstr)-strlen(hexstr)-1);
    1.52 +            strncat(charstr, " ", sizeof(charstr)-strlen(charstr)-1);
    1.53 +        }
    1.54 +        p++; /* next byte */
    1.55 +    }
    1.56 +
    1.57 +    if (strlen(hexstr) > 0) {
    1.58 +        /* print rest of buffer if not empty */
    1.59 +        printf("[%4.4s]   %-50.50s  %s\n", addrstr, hexstr, charstr);
    1.60 +    }
    1.61 +}
    1.62 +