Last active
May 6, 2025 23:17
-
-
Save juandesant/c7eeffb032abd7024a1096ff82931d80 to your computer and use it in GitHub Desktop.
Hexdump in python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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)}") |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Revision 2 fixes an issue with groupings shorter than 16 characters, and creates a
map_byte_to_readable_charfunction to make therow_charslist comprehension more readable.