hexdump.c utility

November 9, 2009

Dump files out in hex format.
Useful for displaying binary files and debugging weird input/output.

Example usages:
  $ hd unicode.txt
  $ cat unicode.txt | hd

/* Name:         $Id: hd.c,v 1.1 2003/05/02 23:56:11 howard Exp $
 * Synopsis:     hd file ...
 * Description:  Dump files in hex/ascii format.
 */

#include <stdio.h>
#include <ctype.h>

#define SEP ' '
#define SEP2 ' '
#define SEP3 "  "


static void
chardump(int *buf, int len)
{
        int indx = 0;

        for (indx = 0; indx < len; ++indx) {
                if (isprint(buf[indx]))
                        putchar(buf[indx]);
                else
                        putchar('.');
        }
}


static int
nibble2hex(int nibble)
{
        switch(nibble) {
          case 0: return '0';
          case 1: return '1';
          case 2: return '2';
          case 3: return '3';
          case 4: return '4';
          case 5: return '5';
          case 6: return '6';
          case 7: return '7';
          case 8: return '8';
          case 9: return '9';
          case 10: return 'A';
          case 11: return 'B';
          case 12: return 'C';
          case 13: return 'D';
          case 14: return 'E';
          case 15: return 'F';
        }
        
}
static void
hexdump(int ch)
{
        putchar(nibble2hex((ch >> 4) & 0xF));
        putchar(nibble2hex(ch & 0xF));
        putchar(SEP);
}


static int
dump(FILE *fp)
{
        int indx = 0;
        int buf[16];

        memset(buf, 0, sizeof(buf));
        while ((buf[indx] = fgetc(fp)) != EOF) {
                hexdump(buf[indx++]);
                if (indx == 8)
                        putchar(SEP2);
                else if (indx == 16) {
                        fputs(SEP3, stdout);
                        chardump(buf, indx);
                        putchar('\n');
                        indx = 0;
                }
        }
        if (indx > 0) {
                int indx2;
                for (indx2 = indx; indx2 < 16; ++indx2) {
                        if (indx2 == 8) { putchar(SEP2); }
                        putchar(' '); putchar(' '); putchar(SEP);
                }
                fputs(SEP3, stdout);
                chardump(buf, indx);
                putchar('\n');
        }
        return 0;
}


main(int argc, char *argv[])
{
        int indx;
        FILE *fp;

        if (argc == 1) {
                dump(stdin);
        } else {
                for (indx = 1; indx < argc; ++indx) {
                        if (fp = fopen(argv[indx], "rb")) {
                                dump(fp);
                                fclose(fp);
                        }
                }
        }
        exit(0);
}
/*
:!cc % -o hd
:!gcc -g % -o hd
*/

Advertisements