I wrote the following hexdump generator function. How can I improve it?
FMT = '{} {} |{}|'
def hexdump_gen(byte_string, _len=16, n=0, sep='-'):
while byte_string[n:]:
col0, col1, col2 = format(n, '08x'), [], ''
for i in bytearray(byte_string[n:n + _len]):
col1 += [format(i, '02x')]
col2 += chr(i) if 31 < i < 127 else '.'
col1 += [' '] * (_len - len(col1))
col1.insert(_len // 2, sep)
yield FMT.format(col0, ' '.join(col1), col2)
n += _len
Example:
In[15]: byte_string = b'W\x9a9\x81\xc2\xb5\xb9\xce\x02\x979\xb5\x19\xa0' \
...: b'\xb9\xca\x02\x979\xb5\x19\xa0\xb9\xca\x02\x979' \
...: b'\xb5\x19\xa0\xb9\xca\x8c\x969\xfb\x89\x8e\xb9' \
...: b'\nj\xb19\x81\x18\x84\xb9\x95j\xb19\x81\x18\x84' \
...: b'\xb9\x95j\xb19\x81\x18\x84\xb9\x95j\xb19\x81\x18' \
...: b'\x84\xb9\x95j\xb19\x81\x18\x84\xb9\x95'
...:
In[16]: from hexdump import hexdump_gen
In[17]: for i in hexdump_gen(byte_string, n=32, sep=''):
...: print(i)
...:
00000020 8c 96 39 fb 89 8e b9 0a 6a b1 39 81 18 84 b9 95 |..9.....j.9.....|
00000030 6a b1 39 81 18 84 b9 95 6a b1 39 81 18 84 b9 95 |j.9.....j.9.....|
00000040 6a b1 39 81 18 84 b9 95 6a b1 39 81 18 84 b9 95 |j.9.....j.9.....|
Tested in CPython 3.6 on Windows 10.