Hex Dump Formatted Byte Rows

Slice a byte payload into fixed-width rows of offset, two-digit hex, and printable characters so binary data stays readable in logs.

PythonData Integrity

Code

pythonsnippet
16 lines
def hex_dump(data, width=16):
    """Render bytes as formatted offset / hex / printable-rows like xxd."""
    for offset in range(0, len(data), width):
        chunk = data[offset:offset + width]
        hex_part = " ".join(f"{byte:02x}" for byte in chunk)
        text_part = "".join(chr(byte) if 32 <= byte < 127 else "." for byte in chunk)
        yield f"{offset:08x}  {hex_part:<{width * 3 - 1}}  |{text_part}|"

payload = b"GIF89a" + bytes([1, 0, 1, 0, 0, 255, 0, 44, 0, 0, 3, 1, 124, 1])
for row in hex_dump(payload):
    print(row)
print("total bytes:", len(payload))

print("width 8:")
for row in hex_dump(payload, width=8):
    print(row)

Output

Captured from a sandboxed run of this snippet in the build pipeline.

00000000  47 49 46 38 39 61 01 00 01 00 00 ff 00 2c 00 00  |GIF89a.......,..|
00000010  03 01 7c 01                                      |..|.|
total bytes: 20
width 8:
00000000  47 49 46 38 39 61 01 00  |GIF89a..|
00000008  01 00 00 ff 00 2c 00 00  |.....,..|
00000010  03 01 7c 01              |..|.|

A closer look

Under the hood: the function hex_dump.

Iteration happens inside for offset in range(0, len(data), width) — everything outside it runs once.

Points of care

  • Nothing resolves through a package manager — calls land on built-in APIs.

Applying it

The entry-point signature is def hex_dump(data, width=16)

The file tags its output — total bytes:, width 8: — when the file runs.

Treat hex_dump as the API: import it, and ignore the supporting code.

Interactive Tools for This Topic

FAQ

Is a package install part of the setup?
No. Installation is unnecessary because only built-in APIs are used. The file defines `hex_dump` at load time.