Back
+30 XP
Concept

Hex Dump Formatter (hexdump -C style)

Debugging binary network packets and corrupt files requires clear visual inspection. A canonical hex dump formats bytes into 16-byte rows: printing 8-hex-digit offsets, spaced two-character hex values, and an ASCII representation where non-printable control characters are masked to `.` 🔬💾⚡.

python
def mini_dump(raw, step=8):
    for i in range(0, len(raw), step):
        chunk = raw[i:i+step]
        hex_str = " ".join(f"{b:02x}" for b in chunk).ljust(step*3-1)
        asc = "".join(chr(b) if 32 <= b <= 126 else "." for b in chunk)
        print(f"{i:04x}  {hex_str}  |{asc}|")

mini_dump(b"Packet\x00\xffOK")

# 12. Hex Dump Formatter (hexdump -C style) When a binary TCP packet arrives truncated or an encrypted AES payload throws authentication tag failures, looking at raw byte arrays like `b'\x1f\x8b\x08\x00...'` in a single unformatted line gives zero spatial orientation 🛑. ```text # Canonical Hex Dump Format: 00000000 48 65 6c 6c 6f 2c 20 50 79 74 68 6f 6e 20 33 2e |Hello, Python 3.| 00000010 31 33 21 00 01 02 0a 45 6e 64 |13!....End| |-------| |---------------------------------------------| |----------------| Offset Hex Byte Pairs (16/row) ASCII Representation ``` ### Canonical Dump Invariants 1. **8-Digit Hex Offset**: The leftmost column displays byte offsets padded to 8 hex digits (`{offset:08x}`). 2. **Normalized Padding**: The hex column must always span the exact same width (`chunk_size * 3 - 1`), even for the final incomplete row, so the right-hand ASCII column stays perfectly aligned. 3. **Safe Printable ASCII**: Check `32 <= b <= 126`. Null bytes (`0x00`), line feeds (`0x0A`), and control characters render cleanly as periods (`.`) 🔬💾⚡. --- ### Interactive Pop-Quiz 🧠 #### Why are non-printable byte values (such as 0x00 through 0x1f and 0x7f to 0xff) masked to dots (.) in the ASCII view? - [ ] Control codes (like bell, newline, backspace) would disrupt terminal formatting or render as invisible missing glyphs 🔬 - [ ] Because non-printable bytes are encrypted - [ ] ASCII encoding only supports 16 total characters - [ ] The terminal emulator halts execution if a null byte is printed --- ### Practical Challenge 🎯 Implement `hex_dump(data: bytes, chunk_size: int = 16) -> str` formatting binary data into canonical rows: `'{offset:08x} {hex_padded} |{ascii_chars}|'`. Replace bytes outside range `[32, 126]` with `'.'`. Pad hex spacing to `chunk_size * 3 - 1` spaces on the last partial chunk. Test with `b'Hello, Python 3.13!\x00\x01\x02\nEnd'`, assert expected output structure, and print the hex dump. <details> <summary>Solution</summary> ```python def hex_dump(data: bytes, chunk_size: int = 16) -> str: lines = [] for offset in range(0, len(data), chunk_size): chunk = data[offset : offset + chunk_size] hex_parts = [f"{b:02x}" for b in chunk] hex_str = " ".join(hex_parts).ljust(chunk_size * 3 - 1) ascii_str = "".join(chr(b) if 32 <= b <= 126 else "." for b in chunk) lines.append(f"{offset:08x} {hex_str} |{ascii_str}|") return "\n".join(lines) payload = b"Hello, Python 3.13!\x00\x01\x02\nEnd" output = hex_dump(payload) assert "00000000 48 65 6c 6c 6f 2c 20 50 79 74 68 6f 6e 20 33 2e |Hello, Python 3.|" in output assert output.endswith("|13!....End|") print(output) ``` </details>

Checkpoint

Why are non-printable byte values (such as `0x00` through `0x1f` and `0x7f` to `0xff`) masked to dots (`.`) in the ASCII view? 🧠

Practice

Implement `hex_dump(data: bytes, chunk_size: int = 16) -> str` formatting binary data into canonical rows: `'{offset:08x} {hex_padded} |{ascii_chars}|'`. Replace bytes outside range `[32, 126]` with `'.'`. Pad hex spacing to `chunk_size * 3 - 1` spaces on the last partial chunk. Test with `b'Hello, Python 3.13!\x00\x01\x02\nEnd'`, assert expected output structure, and print the hex dump. 🎯

Terminal
01
Tap code blocks below to assemble
Available Blocks