summaryrefslogtreecommitdiff
path: root/hexdump.py
blob: cbba3c90904ef88d9775d3a1e5d6538b3d35b649 (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
35
36
37
38
39
40
41
42
43
44
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')

def strescape(txt):
    if type(txt)==bytes:
        txt = txt.decode('cp1251')
    txt = txt.replace("\\", "\\\\")
    txt = txt.replace("\n", "\\n")
    txt = txt.replace("\r", "\\r")
    txt = txt.replace("\t", "\\t")
    txt = txt.replace("\"", "\\\"")
    return txt