Skip to content

Instantly share code, notes, and snippets.

@juandesant
Last active May 6, 2025 23:17
Show Gist options
  • Select an option

  • Save juandesant/c7eeffb032abd7024a1096ff82931d80 to your computer and use it in GitHub Desktop.

Select an option

Save juandesant/c7eeffb032abd7024a1096ff82931d80 to your computer and use it in GitHub Desktop.
Hexdump in python
def hexdump(byte_stream, encoding='utf-8', grouping=16):
num_bytes = len(byte_stream)
padding = (grouping-num_bytes%grouping)%grouping
byte_stream += bytes(chr(0)*padding, encoding)
def map_byte_to_readable_char(the_byte, valid_range=range(32,128), invalid_char='.'):
return chr(the_byte) if the_byte in valid_range else invalid_char
for row in range(0,len(byte_stream)//grouping):
row_data = [f"{byte_stream[row*grouping+n]:02x}" for n in range(0,grouping)]
row_chars = [
f"{map_byte_to_readable_char(byte_stream[row*grouping+n])}"
for n in range(0,grouping)
]
print(f"{row:06x}: {' '.join(row_data)} {''.join(row_chars)}")
@juandesant
Copy link
Author

juandesant commented May 6, 2025

Revision 2 fixes an issue with groupings shorter than 16 characters, and creates a map_byte_to_readable_char function to make the row_chars list comprehension more readable.

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