Last active
April 26, 2021 20:49
-
-
Save 7h3rAm/5603718 to your computer and use it in GitHub Desktop.
hexdump implementation in Python
This file contains hidden or 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
#!/usr/bin/env python3 | |
def hexdump(src, length=16, sep='.'): | |
""" | |
>>> print(hexdump('\x01\x02\x03\x04AAAAAAAAAAAAAAAAAAAAAAAAAABBBBBBBBBBBBBBBBBBBBBBBBBB')) | |
00000000: 01 02 03 04 41 41 41 41 41 41 41 41 41 41 41 41 |....AAAAAAAAAAAA| | |
00000010: 41 41 41 41 41 41 41 41 41 41 41 41 41 41 42 42 |AAAAAAAAAAAAAABB| | |
00000020: 42 42 42 42 42 42 42 42 42 42 42 42 42 42 42 42 |BBBBBBBBBBBBBBBB| | |
00000030: 42 42 42 42 42 42 42 42 |BBBBBBBB| | |
>>> | |
>>> print(hexdump(b'\x01\x02\x03\x04AAAAAAAAAAAAAAAAAAAAAAAAAABBBBBBBBBBBBBBBBBBBBBBBBBB')) | |
00000000: 01 02 03 04 41 41 41 41 41 41 41 41 41 41 41 41 |....AAAAAAAAAAAA| | |
00000010: 41 41 41 41 41 41 41 41 41 41 41 41 41 41 42 42 |AAAAAAAAAAAAAABB| | |
00000020: 42 42 42 42 42 42 42 42 42 42 42 42 42 42 42 42 |BBBBBBBBBBBBBBBB| | |
00000030: 42 42 42 42 42 42 42 42 |BBBBBBBB| | |
""" | |
FILTER = ''.join([(len(repr(chr(x))) == 3) and chr(x) or sep for x in range(256)]) | |
lines = [] | |
for c in range(0, len(src), length): | |
chars = src[c:c+length] | |
hexstr = ' '.join(["%02x" % ord(x) for x in chars]) if type(chars) is str else ' '.join(['{:02x}'.format(x) for x in chars]) | |
if len(hexstr) > 24: | |
hexstr = "%s %s" % (hexstr[:24], hexstr[24:]) | |
printable = ''.join(["%s" % ((ord(x) <= 127 and FILTER[ord(x)]) or sep) for x in chars]) if type(chars) is str else ''.join(['{}'.format((x <= 127 and FILTER[x]) or sep) for x in chars]) | |
lines.append("%08x: %-*s |%s|" % (c, length*3, hexstr, printable)) | |
return '\n'.join(lines) | |
if __name__ == "__main__": | |
print(hexdump('\x01\x02\x03\x04AAAAAAAAAAAAAAAAAAAAAAAAAABBBBBBBBBBBBBBBBBBBBBBBBBB')) | |
print(hexdump(b'\x01\x02\x03\x04AAAAAAAAAAAAAAAAAAAAAAAAAABBBBBBBBBBBBBBBBBBBBBBBBBB')) |
A tweak on this for Python3, assuming input is bytes, using .format()
and padding spaces into the printable column where the buffer ends out of bytes:
https://gist.github.com/mzpqnxow/a368c6cd9fae97b87ef25f475112c84c
Really great snippet! Thank you! Just a small feedback, it would be better to rename hex
to something else since hex
is a python built-in function.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Fixed this to print backslash instead of
sep
:https://gist.github.com/JonathonReinhart/509f9a8094177d050daa84efcd4486cb