Created
August 24, 2021 17:21
-
-
Save CRImier/2fd608703ade9a2a97fbb334ea43fb50 to your computer and use it in GitHub Desktop.
i2cdetect-style hexdump in Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def hexdump(data=None, col_width=16): | |
#This function follows the i2cdump output format, as it's the most readable out there | |
if data is None: data = d | |
# character conversion function | |
conv = lambda x: chr(x) if x in range(0x20, 0x7f) else '.' | |
# getting row count | |
row_count = ceil(len(data)/col_width) | |
max_row_num_len_hex = len(hex(row_count)[2:]) | |
# first line - header | |
hex_digits = [hex(i)[2:] for i in range(16)] | |
hex_cols = " ".join(hex_digits) | |
ascii_cols = "".join(hex_digits) | |
print("{} {}\t {}".format(" "*(max_row_num_len_hex+1), hex_cols, ascii_cols)) | |
# next lines: actual data | |
for r in range(row_count): | |
line = data[r*col_width:][:col_width] | |
line_num_hex = hex(r*col_width)[2:].zfill(max_row_num_len_hex) | |
# if c TODO insert "row ends" check here | |
hex_values = " ".join((hex(b)[2:].zfill(2) for b in line)) | |
ascii_values = "".join(conv(b) for b in line) | |
# in last row, if there are not enough elements to fill the row, we'll need spaces | |
lacking_elements = col_width-len(line) | |
spaces = " "*3*lacking_elements | |
print("{}: {}{}\t {}".format(line_num_hex, hex_values, spaces, ascii_values)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment