Skip to content

Instantly share code, notes, and snippets.

@devilholk
Last active March 11, 2021 20:12
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 devilholk/6cee3ae09d4f0c49e3a7fa0cba40ae85 to your computer and use it in GitHub Desktop.
Save devilholk/6cee3ae09d4f0c49e3a7fa0cba40ae85 to your computer and use it in GitHub Desktop.
Function for creating a human readable hexdump from an iterator of bytes (bytes, bytearray, ctypes buffers etc)
def hexdump(buf, size, minor_width=4, major_width=12, addr_len=4, ljust_char='·', unprintable_char='�', indent=''):
lines = list()
disp = ''
hexa = ''
row_start = 0
for i, c in zip(range(size), buf):
if i % major_width == 0:
addr = f'{hex(row_start)[2:].zfill(addr_len)}: '
row_start = i
if i and (i % major_width == 0):
lines.append(f'{indent}{addr}{disp} | {hexa} |')
hexa = ''
disp = ''
elif i and (i % minor_width == 0):
hexa += ' ' #Insert extra space
if isinstance(c, bytes):
assert len(c) == 1
c = ord(c)
if c < 0x20:
#C0 control codes ( https://en.wikipedia.org/wiki/Unicode_control_characters#Control_pictures )
disp += chr(c) if c >= 32 else chr(0x2400 + c)
elif 0x80 <= c <= 0x9F:
#C1 control codes - just replace
disp += unprintable_char
else:
disp += chr(c)
if hexa:
hexa += ' '
hexa += str(hex(c)[2:]).zfill(2)
if disp:
addr = f'{hex(row_start)[2:].zfill(addr_len)}: '
ljust_hexa = hexa
offset = i % major_width
for missing in range(major_width - offset - 1):
i = missing + offset + 1
if i % minor_width == 0:
ljust_hexa += ' '
ljust_hexa += ' ' + ljust_char * 2
lines.append(f'{indent}{addr}{disp.ljust(major_width, ljust_char)} | {ljust_hexa} |')
return '\n'.join(lines)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment