Hexadecimal display of a byte stream
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)
|
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.
Tags: text
Small Improvements.
This version is unicode-aware, but makes no attempt to display characters outside the 7-bit printable ASCII range -- too difficult in a Windows console.