Skip to content

Instantly share code, notes, and snippets.

@sfaleron
Created September 24, 2015 23:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sfaleron/be869e5d1939d27303b0 to your computer and use it in GitHub Desktop.
Save sfaleron/be869e5d1939d27303b0 to your computer and use it in GitHub Desktop.
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
Copy link
Author

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