Created
September 24, 2015 23:40
-
-
Save sfaleron/be869e5d1939d27303b0 to your computer and use it in GitHub Desktop.
Python function to create a hexdump inspired by old DOS DEBUG command
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
_fmtinner = ('',' ') * 3 + ('','-') + ('',' ') * 3 + ('','') | |
_fmtouter = (' ', ' |', '|') | |
def _mkhex(d, i): | |
try: | |
return '%02x' % (ord(d[i]),) | |
except IndexError: | |
return ' ' | |
def _mkchar(d, i): | |
try: | |
c = d[i] | |
if 31 < ord(c) < 127: | |
return c | |
else: | |
return '.' | |
except IndexError: | |
return ' ' | |
# n is the number of digits in the address field, minimum is two. | |
# length of each line is 63, for n<3, then one more character for each n>=3 | |
def prettify_binary(data, n=None): | |
inputsize = len(data) | |
if not n: | |
n = ln2(max(0, inputsize-1), 4) | |
lines, rmdr = divmod(inputsize, 16) | |
if rmdr: | |
lines += 1 | |
return '\n'.join([''.join(kk) for kk in [sum(zip(k, _fmtouter),()) for k in [ | |
[ | |
'%%0%dx0' % (n-1,) % (i,), | |
''.join(sum(zip([_mkhex(data, 16*i+j) for j in range(16)], _fmtinner), ())), | |
''.join([_mkchar(data, 16*i+j) for j in range(16)]) | |
] for i in range(lines)] ]]) | |
if __name__ == '__main__': | |
import sys | |
print prettify_binary(sys.stdin.read()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is a dependency:
https://gist.github.com/sfaleron/1f958c6e37f4f235d5c8