ActiveState Code

Recipe 142812: Hex dumper


Hexadecimal display of a byte stream

Python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
FILTER=''.join([(len(repr(chr(x)))==3) and chr(x) or '.' for x in range(256)])

def dump(src, length=8):
    N=0; result=''
    while src:
       s,src = src[:length],src[length:]
       hexa = ' '.join(["%02X"%ord(x) for x in s])
       s = s.translate(FILTER)
       result += "%04X   %-*s   %s\n" % (N, length*3, hexa, s)
       N+=length
    return result

s=("This 10 line function is just a sample of pyhton power "
   "for string manipulations.\n"
   "The code is \x07even\x08 quite readable!")

print dump(s)

Discussion

This function produce a classic 3 columns hex dump of a string. * The first column print the offset in hexadecimal. * The second colmun print the hexadecimal byte values. * The third column print ASCII values or a dot for non printable characters.

Comments

  1. 1. At 3:55 p.m. on 24 sep 2005, Raymond Hettinger said:

    Small Improvements.

    def dump2(src, length=8):
        result=[]
        for i in xrange(0, len(src), length):
           s = src[i:i+length]
           hexa = ' '.join(["%02X"%ord(x) for x in s])
           printable = s.translate(FILTER)
           result.append("%04X   %-*s   %s\n" % (i, length*3, hexa, printable))
        return ''.join(result)
    

Sign in to comment