-
-
Save JonathonReinhart/509f9a8094177d050daa84efcd4486cb to your computer and use it in GitHub Desktop.
hexdump implementation in Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import string | |
def hexdump(src, length=16, sep='.'): | |
DISPLAY = string.digits + string.letters + string.punctuation | |
FILTER = ''.join(((x if x in DISPLAY else '.') for x in map(chr, 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]) | |
if len(hex) > 24: | |
hex = "%s %s" % (hex[:24], hex[24:]) | |
printable = ''.join(["%s" % FILTER[ord(x)] for x in chars]) | |
lines.append("%08x: %-*s |%s|\n" % (c, length*3, hex, printable)) | |
print ''.join(lines) | |
if __name__ == '__main__': | |
data = ''.join(chr(x) for x in range(256)) | |
hexdump(data) |
That's really a nice version of hexdump, since you can get it in the form of return and print it at once.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Updated from forked version:
string
instead of thelen(repr(chr(x))) == 3
trick which didn't work for backslash. This is clearer now.FILTER
when making theprintable
part; theord(x) < 127
part was unnecessary, sinceFILTER
contains 256 entries.