1 from .py3compat import byte2int, int2byte, bytes2str
4 # Map an integer in the inclusive range 0-255 to its string byte representation
5 _printable = dict((i, ".") for i in range(256))
6 _printable.update((i, bytes2str(int2byte(i))) for i in range(32, 128))
9 def hexdump(data, linesize):
11 data is a bytes object. The returned result is a string.
15 fmt = "%%04X %%-%ds %%s"
17 fmt = "%%08X %%-%ds %%s"
18 fmt = fmt % (3 * linesize - 1,)
19 for i in range(0, len(data), linesize):
20 line = data[i : i + linesize]
21 hextext = " ".join('%02x' % byte2int(b) for b in line)
22 rawtext = "".join(_printable[byte2int(b)] for b in line)
23 prettylines.append(fmt % (i, str(hextext), str(rawtext)))
27 class HexString(bytes):
29 Represents bytes that will be hex-dumped to a string when its string
30 representation is requested.
32 def __init__(self, data, linesize = 16):
33 self.linesize = linesize
35 def __new__(cls, data, *args, **kwargs):
36 return bytes.__new__(cls, data)
42 return sep + sep.join(
43 hexdump(self, self.linesize))