Browse Source

pretty_hexdump() -> block_format()

The MMGen Project 5 years ago
parent
commit
04a1dcaae4
2 changed files with 15 additions and 8 deletions
  1. 1 1
      mmgen/tool.py
  2. 14 7
      mmgen/util.py

+ 1 - 1
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()

+ 14 - 7
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)