summaryrefslogtreecommitdiff
path: root/hexdump.py
blob: aeb8c881bf19ce0a5dc18ed286b629b692473293 (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
28
29
30
31
32
33
34
import struct
from binascii import b2a_hex, a2b_hex
"""
Simple hexdump, 16 bytes per line with offset.
"""

def unhex(data):
    if type(data)==bytes:
        data = data.decode('ascii')
    data = data.replace(' ', '')
    data = data.strip()
    return a2b_hex(data)

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')