From 04a1dcaae40fc9c316a9a15db8ca862b904b161c Mon Sep 17 00:00:00 2001 From: The MMGen Project Date: Sun, 27 Oct 2019 16:12:20 +0000 Subject: [PATCH] pretty_hexdump() -> block_format() --- mmgen/tool.py | 2 +- mmgen/util.py | 21 ++++++++++++++------- 2 files changed, 15 insertions(+), 8 deletions(-) diff --git a/mmgen/tool.py b/mmgen/tool.py index 8dd5c770..1307488c 100755 --- a/mmgen/tool.py +++ b/mmgen/tool.py @@ -275,7 +275,7 @@ class MMGenToolCmdUtil(MMGenToolCmdBase): "convert hexadecimal value to bytes (warning: outputs binary data)" return bytes.fromhex(hexstr) - def hexdump(self,infile:str,cols=8,line_nums=True): + def hexdump(self,infile:str,cols=8,line_nums='hex'): "create hexdump of data from file (use '-' for stdin)" data = get_data_from_file(infile,dash=True,quiet=True,binary=True) return pretty_hexdump(data,cols=cols,line_nums=line_nums).rstrip() diff --git a/mmgen/util.py b/mmgen/util.py index 9a4a845e..a1aee67b 100755 --- a/mmgen/util.py +++ b/mmgen/util.py @@ -476,16 +476,23 @@ def pretty_format(s,width=80,pfx=''): s = s[i+1:] return pfx + ('\n'+pfx).join(out) -def pretty_hexdump(data,gw=2,cols=8,line_nums=False): - r = (0,1)[bool(len(data) % gw)] +def block_format(data,gw=2,cols=8,line_nums=None,data_is_hex=False): + assert line_nums in (None,'hex','dec'),"'line_nums' must be one of None, 'hex' or 'dec'" + ln_fs = '{:06x}: ' if line_nums == 'hex' else '{:06}: ' + bytes_per_chunk = gw + if data_is_hex: + gw *= 2 + nchunks = len(data)//gw + bool(len(data)%gw) return ''.join( - [ - ('' if (line_nums == False or i % cols) else '{:06x}: '.format(i*gw)) + - data[i*gw:i*gw+gw].hex() + ('\n',' ')[bool((i+1) % cols)] - for i in range(len(data)//gw + r) - ] + ('' if (line_nums == None or i % cols) else ln_fs.format(i*bytes_per_chunk)) + + data[i*gw:i*gw+gw] + + (' ' if (i+1) % cols else '\n') + for i in range(nchunks) ).rstrip() + '\n' +def pretty_hexdump(data,gw=2,cols=8,line_nums=None): + return block_format(data.hex(),gw,cols,line_nums,data_is_hex=True) + def decode_pretty_hexdump(data): from string import hexdigits pat = r'^[{}]+:\s+'.format(hexdigits)