Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Python function to create a hexdump inspired by old DOS DEBUG command
_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())
@sfaleron

This comment has been minimized.

Copy link
Owner Author

sfaleron commented Sep 24, 2015

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.