简体   繁体   中英

Trying to convert a hexdump from Python2 to Python3

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.

This worked for me. Changed the xrange to range, isinstance isn't really necessary but 2to3 suggested it. Removed byte strings.

def hexdump(src, length=16):
  result = []
  digits = 4 if isinstance(src, str) else 2
  for i in range(0, len(src), length):
   s = src[i:i+length]
   hexa = " ".join(map("{0:0>2X}".format,src))
   text = "".join([chr(x) if 0x20 <= x < 0x7F else "." for x in s])
   result.append("%04X   %-*s   %s" % (i, length*(digits + 1), hexa, text) )
  return "\n".join(result)
def hexdump(src, length=16):
    result = []
    digits = 4

    s = src[:]
    print(s)
    hexa = " ".join(["%0*X" % (digits, ord(x)) for x in s.decode("ascii")])
    text = "".join([x if 0x20 <= ord(x) < 0x7F else "." for x in s.decode("ascii")])
    result.append("%04X   %-*s   %s" % (1, length * (digits + 1), hexa, text))

    print("\n".join(result))

This is what you need.

The function from the book is doing unnecessary things just to confuse you. not to bash on the book but the code in that book is slightly bad.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM