← 中文资源

简体中文版本

字节载荷十六进制转储

把字节载荷按固定宽度切成多行,渲染偏移量、两位十六进制与可打印字符(不可打印用点占位),日志里检视二进制内容就靠这种行式转储。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

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              |..|.|

实现说明

逻辑集中在函数 hex_dump里。 for offset in range(0, len(data), width) 是唯一的迭代点——其余代码顺序执行一遍。

使用要点

  • 演示输出是带标签的(total bytes:、width 8:),每个操作都会留下自己的一行标注。
  • 值得导入的表面是 hex_dump;周围的辅助代码对片段是私有的。

常见问题

安装包是准备工作的一部分吗?

不需要。只用内建 API,安装这一步可以省掉。 文件在加载时定义 hex_dump。

主签名形如 def hex_dump(data, width=16)

代码示例

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)