Objective
Develop a Python program to create a "dump" utility: a hex viewer that displays the contents of a file, with 16 bytes in each row and 24 rows in each screen. The program should pause after displaying each screen before showing the next 24 rows.
In each row, the 16 bytes should be displayed first in hexadecimal format and then as characters. Bytes with an ASCII code less than 32 should be shown as a dot instead of the corresponding non-printable character.
You can search for "hex editor" on Google Images to see an example of the expected appearance.
Example Python Exercise
Show Python Code
# Python program to create a hex viewer for files
def hex_viewer(file_path):
try:
# Open the file in binary read mode
with open(file_path, 'rb') as file:
# Row and screen counters
row_count = 0
screen_count = 0
while True:
# Read 16 bytes at a time
chunk = file.read(16)
# Break the loop if no more data is left
if not chunk:
break
# Display the offset (row start position)
print(f"{row_count * 16:08X}: ", end="")
# Display the chunk in hexadecimal format
hex_representation = " ".join(f"{byte:02X}" for byte in chunk)
print(f"{hex_representation:<48}", end=" ")
# Display the chunk as ASCII characters
ascii_representation = "".join(
chr(byte) if 32 <= byte <= 126 else "." for byte in chunk
)
print(ascii_representation)
# Increment row count
row_count += 1
# Pause after displaying 24 rows (one screen)
if row_count % 24 == 0:
screen_count += 1
input(f"-- Screen {screen_count} (Press Enter to continue) --")
# Final message after the dump is complete
print("-- End of file --")
except FileNotFoundError:
print(f"Error: The file '{file_path}' was not found.")
except Exception as e:
print(f"Error: {str(e)}")
# Example usage
hex_viewer("example_file.bin")
Output
Example Input File (example_file.bin):
Binary content (can be any type of file):
Hello, World! This is a test file.
1234567890abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()
Example Output:
00000000: 48 65 6C 6C 6F 2C 20 57 6F 72 6C 64 21 20 54 68 Hello, World! Th
00000010: 69 73 20 69 73 20 61 20 74 65 73 74 20 66 69 6C is is a test fil
00000020: 65 2E 0A 31 32 33 34 35 36 37 38 39 30 61 62 63 e..1234567890abc
00000030: 64 65 66 67 68 69 6A 6B 6C 6D 6E 6F 70 71 72 73 defghijklmnopqrs
00000040: 74 75 76 77 78 79 7A 0A 41 42 43 44 45 46 47 48 tuvwxyz.ABCDEFGH
00000050: 49 4A 4B 4C 4D 4E 4F 50 51 52 53 54 55 56 57 58 IJKLMNOPQRSTUVWX
00000060: 59 5A 21 40 23 24 25 5E 26 2A 28 29 YZ!@#$%^&*()
-- Screen 1 (Press Enter to continue) --
-- End of file --
Share this Python Exercise