Skip to content

Instantly share code, notes, and snippets.

@sbz
Created July 13, 2011 13:04
Show Gist options
  • Save sbz/1080258 to your computer and use it in GitHub Desktop.
Save sbz/1080258 to your computer and use it in GitHub Desktop.
hexdump implementation in Python
def hexdump(src, length=16):
FILTER = ''.join([(len(repr(chr(x))) == 3) and chr(x) or '.' for x in range(256)])
lines = []
for c in xrange(0, len(src), length):
chars = src[c:c+length]
hex = ' '.join(["%02x" % ord(x) for x in chars])
printable = ''.join(["%s" % ((ord(x) <= 127 and FILTER[ord(x)]) or '.') for x in chars])
lines.append("%04x %-*s %s\n" % (c, length*3, hex, printable))
return ''.join(lines)
@sbz
Copy link
Author

sbz commented Jul 13, 2011

Originally come from my old tweet [1] paste on codepad [2]

[1] https://twitter.com/sbrabez/statuses/15311796519
[2] http://codepad.org/ekfw3UZg

@7h3rAm
Copy link

7h3rAm commented May 18, 2013

Thanks for this really handy snippet. I did a quick fix to make its output more like hexdump's. Here is the modified version: https://gist.github.com/7h3rAm/5603718

@1mm0rt41PC
Copy link

1mm0rt41PC commented May 15, 2014

Very good snippet ! Thanks !
I did a port to python3: https://gist.github.com/1mm0rt41PC/c340564823f283fe530b

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment