#!/usr/bin/bash
# bash-hexdump
# by Dennis Williamson - 2010-01-04
# in response to http://stackoverflow.com/questions/2003803/show-hexadecimal-numbers-of-a-file
# usage: bash-hexdump file

if [[ -z "$1" ]]
then
    exec 3<&0                           # read stdin
    [[ -p /dev/stdin ]] || tty="yes"    # no pipe
else
    exec 3<"$1"            # read file
fi

IFS=""                     # disables interpretation of \t, \n and space
LANG=C                     # allows characters > 0x7F
bytecount=0
valcount=0
while read -s -u 3 -d '' -r -n 1 char    # -d '' allows newlines, -r allows \
do
    (( (bytecount % 16) == 0)) && printf "%07x: " $bytecount
    ((bytecount++))
    printf -v val "%02x" "'$char"    # see below for the ' trick
    echo -n "$val"
    (( (bytecount % 2) == 0 )) && echo -n " "
    ((valcount++))
    if [[ "$val" < 20 || "$val" > 7e ]]
    then
        string+="."                  # show unprintable characters as a dot
    else
        string+=$char
    fi
    if (( bytecount % 16 == 0 ))   # print 16 values per line
    then
        echo " $string"
        string=''
        valcount=0
    fi
done

if [[ "$string" != "" ]]            # if the last line wasn't full, pad it out
then
    length=${#string}
    (( length += (17 - valcount) * 3 + 4))
    printf "%${length}s\n" "$string"
fi
