Tiny hex dumper

This commit is contained in:
Nick Chambers 2024-05-03 12:59:19 -05:00
parent 717912cada
commit 5c413c1947
1 changed files with 36 additions and 0 deletions

36
python/hexdump.py Normal file
View File

@ -0,0 +1,36 @@
import sys
def hexdump(data):
printed = []
print(f"{0:08x}", end=" ")
for idx in range(len(data)):
print(f"{data[idx]:02x}", end=" ")
if data[idx] < 129 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:
fmt = ""
if (idx + 1) % 16 != 0:
fmt = " " * (((16 - ((idx + 1) % 16)) * 3) + 1 + int((idx + 1) % 16 < 8))
print(f"{fmt}|{''.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)