So I've been learning Python3 for the last month or so. I'm going through "Black Hat Python" by Justin Seitz right now, but all of the code is in Python2. Most of the code so far was easy to convert to Python3, but I ran across a hexdump function in a tcp_proxy program that has me stumped. Below is the Python2 code from the book.
def hexdump(src, length=16):
result = []
digits = 4 if isinstance(src, unicode) else 2
for i in xrange(0, len(src), length):
s = src[i:i+length]
hexa = b' '.join(["%0*X" % (digits, ord(x)) for x in s])
text = b''.join([x if 0x20 <= ord(x) < 0x7F else b'.' for x in s])
result.append(b"%04X %-*s %s" % (i, length*(digits + 1), hexa, text))
print b'\n'.join(result)
I have a few questions that I haven't been able to find online. Why would digits need to be unpacked if it's a single int? Would the equivalent of "%0*X" % (digits, ord(x))
be "{0:X}".format(*digits, ord(x))
? Why are there two arguments for this? I noticed that there was an additional argument in result.append()
as well. Any help would be greatly appreciated.