Skip to content

Instantly share code, notes, and snippets.

@conioh
Last active August 7, 2018 23:04
Show Gist options
  • Save conioh/35e5b9a43a25e6a01ddb to your computer and use it in GitHub Desktop.
Save conioh/35e5b9a43a25e6a01ddb to your computer and use it in GitHub Desktop.
Hex Editor-style print in Python
import string
def my_esc(s):
printable = string.ascii_letters + string.digits + string.punctuation
return "".join(c if c in printable else "." for c in s)
def hexedit_print(buf, line_size = 0x10):
heading = "Offset(h) " + " ".join(format(n, '02x') for n in range(line_size))
print heading
for i in range(len(buf) / line_size):
line = format(i*line_size, '08x') + " "
for j in range(line_size):
line += buf[i*line_size+j].encode("hex") + " "
line += " " + my_esc(buf[i*line_size:(i+1)*line_size])
print line
final_line_start = len(buf) / line_size * line_size
final_line_len = len(buf) - final_line_start
if final_line_len > 0:
line = format(final_line_start, '08x') + " "
for j in range(final_line_len):
line += buf[final_line_start+j].encode("hex") + " "
line = line.ljust(8 + 2 + 3*line_size, " ")
line += " " + my_esc(buf[final_line_start:len(buf)])
print line
import string
def my_esc(s):
printable = string.ascii_letters + string.digits + string.punctuation
return "".join(chr(c) if chr(c) in printable else "." for c in s)
def hexedit_print(buf, line_size = 0x10):
heading = "Offset(h) " + " ".join(format(n, '02x') for n in range(line_size))
print(heading)
for i in range(int(len(buf) / line_size)):
line = format(i*line_size, '08x') + " "
for j in range(line_size):
line += ("%02x" % buf[i*line_size+j]) + " "
line += " " + my_esc(buf[i*line_size:(i+1)*line_size])
print(line)
final_line_start = int(len(buf) / line_size) * line_size
final_line_len = len(buf) - final_line_start
if final_line_len > 0:
line = format(final_line_start, '08x') + " "
for j in range(final_line_len):
line += ("%02x" % buf[final_line_start+j]) + " "
line = line.ljust(8 + 2 + 3*line_size, " ")
line += " " + my_esc(buf[final_line_start:len(buf)])
print(line)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment