add header to over.core.misc.hexdump

This commit is contained in:
Martinez 2015-08-12 18:30:38 +02:00
parent ca1041c39b
commit 01ef34b519

View file

@ -87,11 +87,12 @@ def debugger():
# -------------------------------------------------- # --------------------------------------------------
def hexdump(data, indent=0, offset=16, show_offsets=True, show_ascii=True, output=sys.stdout): def hexdump(data, indent=0, offset=16, show_header=True, show_offsets=True, show_ascii=True, output=sys.stdout):
""" """
Writes a hex dump of 'data' to 'output'. Writes a hex dump of 'data' to 'output'.
The output text is indented with spaces and contains 'offset' bytes per line. The output text is indented with spaces and contains 'offset' bytes per line.
If show_header is True, a single line with byte numbers preceeds all output.
If show_offsets is True, each line is prefixed with the address of the first byte of that line. If show_offsets is True, each line is prefixed with the address of the first byte of that line.
If show_ascii is True, each line is suffixed with its ASCII representation. Unprintable characters If show_ascii is True, each line is suffixed with its ASCII representation. Unprintable characters
are replaced with a dot. are replaced with a dot.
@ -101,9 +102,24 @@ def hexdump(data, indent=0, offset=16, show_offsets=True, show_ascii=True, outpu
if type(data) is not bytes: if type(data) is not bytes:
raise ValueError('data must be bytes') raise ValueError('data must be bytes')
format_str = '%%0%dx ' %(math.ceil(math.log2(len(data)) / 8) * 2) offset_figures = math.ceil(math.log2(len(data)) / 8) * 2
format_str = '%%0%dx ' %(offset_figures)
ptr = 0 ptr = 0
if show_header:
line = []
if show_offsets:
line.append('offset'[:offset_figures].ljust(offset_figures + 2))
for i in range(offset):
line.append('%2x' %(i))
if show_ascii:
line.append(' ASCII')
output.write(' '.join(line) + '\n')
while data[ptr:]: while data[ptr:]:
if indent: if indent:
output.write(' ' * indent) output.write(' ' * indent)
@ -129,7 +145,7 @@ def hexdump(data, indent=0, offset=16, show_offsets=True, show_ascii=True, outpu
output.write(' '.join(hex_bytes)) output.write(' '.join(hex_bytes))
if show_ascii: if show_ascii:
output.write(' ' + ''.join(ascii_bytes)) output.write(' |' + ''.join(ascii_bytes) + '|')
output.write('\n') output.write('\n')