Skip to content

dumpgen() 与 dehex() ​

🔄 dumpgen 逐行生成 hex dump;dehex 反向把 hex 文本还原成二进制。

📎 源码在线查看:myhexdump.py#L243-L296(dumpgen)

dumpgen ​

python
def dumpgen(binary, size=2, sep=' ')
# 生成器:逐行 yield 格式化的 hex dump 行

hexdump() 的 result='generator' 模式内部就是调 dumpgen。逐行产出:

00000000: 00 00 00 5B 68 65 78 64  75 6D 70 5D 00 00 00 00  ...[hexdump]....
00000010: 00 11 22 33 44 55 66 77  88 99 AA BB CC DD EE FF  .."3DUfw........

每行三栏:

  1. 偏移量(%08X:)
  2. hex 字节(dump() 渲染,每 16 字节,中间多一空格)
  3. ASCII 栏(不可打印字符显示 .)

dehex ​

python
def dehex(hextext)
# "00 DE AD" -> b'\x00\xde\xad'

实现 ​

python
def dehex(hextext):
    if PY3K:
        return bytes.fromhex(hextext)   # Py3 内置,自动忽略空白
    else:
        hextext = "".join(hextext.split())
        return hextext.decode('hex')    # Py2 bytes 的特有方法

Py3 / Py2 分支 ​

版本方法说明
Py3bytes.fromhex(hextext)内置,会自动忽略空白
Py2"".join(hextext.split()) + .decode('hex')Py2 没有 fromhex,先去空白再 decode

用途 ​

restore() 解析 hex dump 还原二进制时用 dehex。r0capture 抓包主流程不直接用 dehex,但作为完整工具链保留。

dump ​

python
def dump(binary, size=2, sep=' ')
# b'\x00\xde\xad' -> "00 DE AD"

dumpgen 每行的 hex 栏由 dump() 生成:

python
hexstr = binascii.hexlify(binary)   # 每字节 -> 两个十六进制字符
if PY3K:
    hexstr = hexstr.decode('ascii') # Py3 hexlify 返回 bytes
hexstr = hexstr.upper()
# 按 size=2 切块用 sep 连起来

binascii.hexlify 比手写 "%02X" % byte 更快更稳。

相关文档 ​

基于 VitePress 构建 · 教学用途