/*
 *  Copyright (c) 2001 Dan Gudmundsson
 *  See the file "license.terms" for information on usage and redistribution
 *  of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 * 
 *     $Id: hexdump.c,v 1.2 2001/11/22 15:09:11 dgud Exp $
 *  Got this from Gordon Beaton
 */
#include <stdio.h>
#include <ctype.h>

#define CHUNK 16

void hexdump(FILE *out, unsigned char *buf, int bufsz)
{
  int i,j;
  int count;

  /* do this in chunks of CHUNK bytes */
  for (i=0; i<bufsz; i+=CHUNK) {
    /* show the offset */
    fprintf(out,"0x%06x  ", i);

    /* max of CHUNK or remaining bytes */
    count = ((bufsz-i) > CHUNK ? CHUNK : bufsz-i);
    
    /* show the bytes */
    for (j=0; j<count; j++) {
      if (j==CHUNK/2) fprintf(out," ");
      fprintf(out,"%02x ",buf[i+j]);
    }
    
    /* pad with spaces if less than CHUNK */
    for (j=count; j<CHUNK; j++) {
      if (j==CHUNK/2) fprintf(out," ");
      fprintf(out,"   ");
    }

    /* divider between hex and ascii */
    fprintf(out," ");
  
    for (j=0; j<count; j++) 
      fprintf(out,"%c",(isprint(buf[i+j]) ? buf[i+j] : '.'));
 
    fprintf(out,"\n\r");
  }
}

