over.core.misc.hexdump
- fix crash on empty data - add option for string output
This commit is contained in:
parent
6d854fefc6
commit
bd216a2e7a
1 changed files with 15 additions and 8 deletions
23
core/misc.py
23
core/misc.py
|
@ -3,6 +3,7 @@
|
|||
|
||||
import copy
|
||||
import imp
|
||||
import io
|
||||
import math
|
||||
import os
|
||||
import sys
|
||||
|
@ -96,13 +97,15 @@ def hexdump(data, indent=0, offset=16, show_header=True, show_offsets=True, show
|
|||
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
|
||||
are replaced with a dot.
|
||||
The 'output' must implement a .write(str) method.
|
||||
The 'output' must implement a .write(str) method. If 'output' is None, the string is returned instead.
|
||||
"""
|
||||
|
||||
output_io = io.StringIO() if not output else output
|
||||
|
||||
if type(data) is not bytes:
|
||||
raise ValueError('data must be bytes')
|
||||
|
||||
offset_figures = math.ceil(math.log2(len(data)) / 8) * 2
|
||||
offset_figures = math.ceil(math.log2(len(data)) / 8) * 2 if data else 2
|
||||
format_str = '%%0%dx ' %(offset_figures)
|
||||
ptr = 0
|
||||
|
||||
|
@ -118,14 +121,14 @@ def hexdump(data, indent=0, offset=16, show_header=True, show_offsets=True, show
|
|||
if show_ascii:
|
||||
line.append(' ASCII')
|
||||
|
||||
output.write(' '.join(line) + '\n')
|
||||
output_io.write(' '.join(line) + '\n')
|
||||
|
||||
while data[ptr:]:
|
||||
if indent:
|
||||
output.write(' ' * indent)
|
||||
output_io.write(' ' * indent)
|
||||
|
||||
if show_offsets:
|
||||
output.write(format_str %(ptr))
|
||||
output_io.write(format_str %(ptr))
|
||||
|
||||
hex_bytes = []
|
||||
ascii_bytes = []
|
||||
|
@ -142,11 +145,15 @@ def hexdump(data, indent=0, offset=16, show_header=True, show_offsets=True, show
|
|||
elif i == len(data):
|
||||
hex_bytes.extend([' '] * (offset - local_i))
|
||||
|
||||
output.write(' '.join(hex_bytes))
|
||||
output_io.write(' '.join(hex_bytes))
|
||||
|
||||
if show_ascii:
|
||||
output.write(' |' + ''.join(ascii_bytes) + '|')
|
||||
output_io.write(' |' + ''.join(ascii_bytes) + '|')
|
||||
|
||||
output.write('\n')
|
||||
output_io.write('\n')
|
||||
|
||||
ptr += offset
|
||||
|
||||
if not output:
|
||||
output_io.seek(0)
|
||||
return output_io.read()
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue