■ ■ ■ ■ ■ ■
Projects/47_hexdump/hexdump.py
| 1 | + | #!/usr/bin/python3 |
| 2 | + | |
| 3 | + | |
| 4 | + | import os |
| 5 | + | import sys |
| 6 | + | import argparse |
| 7 | + | |
| 8 | + | |
| 9 | + | if __name__ == '__main__': |
| 10 | + | parser = argparse.ArgumentParser() |
| 11 | + | parser.add_argument("FILE", help="file to be dump", type=str) |
| 12 | + | parser.add_argument("-b", "--binary", help="display bytes in binary instead of hex", action="store_true") |
| 13 | + | args = parser.parse_args() |
| 14 | + | |
| 15 | + | try: |
| 16 | + | with open(args.FILE, "rb") as f: |
| 17 | + | n = 0 |
| 18 | + | b = f.read(16) |
| 19 | + | filesize = os.path.getsize(args.FILE) |
| 20 | + | print(f"Size {args.FILE}: {filesize} bytes - 0x{filesize:08x}") |
| 21 | + | while b: |
| 22 | + | if not args.binary: |
| 23 | + | s1 = " ".join([f"{i:02x}" for i in b]) # hex string |
| 24 | + | s1 = s1[0:23] + " " + s1[23:] # insert extra space between groups of 8 hex values |
| 25 | + | width = 48 |
| 26 | + | else: |
| 27 | + | s1 = " ".join([f"{i:08b}" for i in b]) |
| 28 | + | s1 = s1[0:71] + " " + s1[71:] |
| 29 | + | width = 144 |
| 30 | + | s2 = "".join([chr(i) if 32 <= i <= 127 else "." for i in b]) # ascii string; chained comparison |
| 31 | + | print(f"{n * 16:08x} {s1:<{width}} |{s2}|") |
| 32 | + | |
| 33 | + | n += 1 |
| 34 | + | b = f.read(16) |
| 35 | + | |
| 36 | + | except Exception as e: |
| 37 | + | print(__file__, ": ", type(e).__name__, " - ", e, sep="", file=sys.stderr) |
| 38 | + | |
| 39 | + | |
| 40 | + | |