grimoire/python/hexdump.py

39 lines
845 B
Python

import sys
def padlen(number):
return ((16 - (number % 16)) * 3) + 1 + int(number % 16 < 8)
def hexdump(data):
printed = []
print(f"{0:08x}", end=" ")
for idx in range(len(data)):
print(f"{data[idx]:02x}", end=" ")
if data[idx] < 128 and chr(data[idx]).isprintable():
printed.append(chr(data[idx]))
else:
printed.append(".")
if (idx + 1) % 8 == 0:
print(end=" ")
if idx == len(data) - 1:
padding = ""
if (idx + 1) % 16 != 0:
padding = " " * padlen(idx + 1)
print(f"{padding}|{''.join(printed)}|")
print(f"{idx + 1:08x}")
elif (idx + 1) % 16 == 0:
print(f"|{''.join(printed)}|")
print(f"{idx + 1:08x}", end=" ")
printed.clear()
if len(sys.argv) > 1:
with open(sys.argv[1], "rb") as handle:
data = handle.read()
hexdump(data)