Skip to content

Instantly share code, notes, and snippets.

@wrenoud
Last active August 29, 2015 14:01
Show Gist options
  • Save wrenoud/a0c25a488d7b5429eb05 to your computer and use it in GitHub Desktop.
Save wrenoud/a0c25a488d7b5429eb05 to your computer and use it in GitHub Desktop.
Prints a formatted hexdump of a binary string
#!/usr/bin/python
"""CLI USAGE: hexdump [-w n] [-ws b] <filename>
-w --words the number of words to display on a line
-ws --word-size the number of bytes to display in a word
"""
import __future__
from StringIO import StringIO
import math
def hexdump(stream, words=4, word_size=4):
use_stream = stream
if isinstance(stream, (str, buffer)):
use_stream = StringIO(stream)
line_len = words * word_size
cuts = int(math.ceil(line_len / float(word_size)))
data = use_stream.read(line_len)
while data:
hexa = " ".join(["{:02x}".format(ord(char)) for char in data])
ascii = "".join([char if ord(char) > 32 and ord(char) < 127 else '.' for char in data])
# add spaces to deliniate words
hexa = hexa.ljust(line_len * 3) # pad with whitespace
hexa = " ".join([hexa[cut*3*word_size:(cut+1)*3*word_size] for cut in range(cuts)])
ascii = ascii.ljust(line_len) # pad with whitespace
ascii = " ".join([ascii[cut*word_size:(cut+1)*word_size] for cut in range(cuts)])
print("| {} | {} |".format(hexa, ascii))
data = use_stream.read(line_len)
if __name__ == "__main__":
import sys
if len(sys.argv) <= 1:
print __doc__
else:
words = 4
word_size = 4
for i, val in enumerate(sys.argv):
if val == "-w" or val == "--words":
words = int(sys.argv[i+1])
elif val == "-ws" or val == "--word-size":
word_size = int(sys.argv[i+1])
hexdump(open(sys.argv[-1]), words, word_size)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment