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........每行三栏:
- 偏移量(
%08X:) - hex 字节(
dump()渲染,每 16 字节,中间多一空格) - 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 分支
| 版本 | 方法 | 说明 |
|---|---|---|
| Py3 | bytes.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 更快更稳。