Skip to content

Instantly share code, notes, and snippets.

@smitelli
Created April 27, 2024 21:37
Show Gist options
  • Save smitelli/c65af6aab5cd96270ca86a24d534e60b to your computer and use it in GitHub Desktop.
Save smitelli/c65af6aab5cd96270ca86a24d534e60b to your computer and use it in GitHub Desktop.
A teeny tiny xxd clone in a ten-line Python function
import math
import re
def hex_dump(data, cols=16):
data_len = len(data)
addr_pad = math.ceil(data_len.bit_length() / 4)
for i in range(0, data_len, cols):
paragraph = data[i:i + cols]
hex_view = paragraph.hex(' ', 1).ljust(cols * 3)
ascii_view = re.sub(rb'[^\x20-\x7f]', b'.', paragraph).decode()
print(f'{i:0{addr_pad}x}: {hex_view} {ascii_view}')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment