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.
Code
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
Hex Dump ViewerPreview any text as a classic hexadecimal dump with byte offsets, sixteen bytes per row, and an ASCII column for quick inspection.Byte Size ConverterShow one byte count in every unit side by side, using decimal (kB/MB/GB) or binary (KiB/MiB/GiB) standards.Bitwise Operations CalculatorCompute AND, OR, XOR, NOT, and shifts on 32-bit unsigned operands with binary, hex, and signed decimal views.CSS Color ConverterConvert colors between HEX, rgb(), and hsl() instantly, with support for shorthand hex and rgb or hsl inputs. Fully offline and dependency free.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.