grimoire/python/hexdump.py

40 lines
845 B
Python
Raw Permalink Normal View History

2024-05-03 17:59:19 +00:00
import sys
2024-05-03 18:13:13 +00:00
def padlen(number):
return ((16 - (number % 16)) * 3) + 1 + int(number % 16 < 8)
2024-05-03 17:59:19 +00:00
def hexdump(data):
printed = []
print(f"{0:08x}", end=" ")
for idx in range(len(data)):
print(f"{data[idx]:02x}", end=" ")
2024-05-03 18:13:13 +00:00
if data[idx] < 128 and chr(data[idx]).isprintable():
2024-05-03 17:59:19 +00:00
printed.append(chr(data[idx]))
else:
printed.append(".")
if (idx + 1) % 8 == 0:
print(end=" ")
if idx == len(data) - 1:
2024-05-03 18:13:13 +00:00
padding = ""
2024-05-03 17:59:19 +00:00
if (idx + 1) % 16 != 0:
2024-05-03 18:13:13 +00:00
padding = " " * padlen(idx + 1)
2024-05-03 17:59:19 +00:00
2024-05-03 18:13:13 +00:00
print(f"{padding}|{''.join(printed)}|")
2024-05-03 17:59:19 +00:00
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)