summaryrefslogtreecommitdiff
path: root/hexdump.py
blob: c119b16be0c1e16cfe1984d7706fefa15c8c5285 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import struct
from binascii import b2a_hex
"""
Simple hexdump, 16 bytes per line with offset.
"""

def ashex(line):
    return " ".join("%02x" % _ for _ in line)
def aschr(b):
    if 32<=b<0x7f:
        return "%c" % b
    elif 0x80<=b<=0xff:
        try:
            c = struct.pack("<B", b).decode('cp1251')
            if c:
                return c
        except:
            pass
    return "."
def asasc(line):
    return "".join(aschr(_) for _ in line)
def hexdump(ofs, data):
    for o in range(0, len(data), 16):
        print("%08x: %-47s  %s" % (o+ofs, ashex(data[o:o+16]), asasc(data[o:o+16])))

def tohex(data):
    return b2a_hex(data).decode('ascii')