Created
April 2, 2013 20:24
-
-
Save mooware/5295858 to your computer and use it in GitHub Desktop.
Python script that takes lines of text containing byte hex values, and appends a printable representation of the bytes to each line. It's similar to xxd, but it takes already dumped bytes instead of the original binary data. Example:
"70 79 74 68 6f 6e" -> "70 79 74 68 6f 6e python"
This file contains 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
#!/usr/bin/env python | |
import fileinput | |
import re | |
# pattern to match lines of hex byte values | |
PATTERN = re.compile("^[a-zA-Z0-9]{1,2}( [a-zA-Z0-9]{1,2})*$") | |
# margin between bytes and text | |
MARGIN = 2 | |
# expected number of bytes for which the text is aligned | |
MINBYTES = 16 | |
# expected width of a line of bytes | |
MINLINELEN = MINBYTES * 3 - 1 | |
# translate hex byte string to printable character | |
def translate(bytestr): | |
value = int(bytestr, 16) | |
if 32 <= value <= 127: | |
return chr(value) | |
else: | |
return "." | |
for line in fileinput.input(): | |
# eat newline | |
line = line.strip() | |
if PATTERN.match(line): | |
# translate the bytes | |
text = "".join(map(translate, line.split(" "))) | |
# calculate the margin | |
linelen = max(MINLINELEN, len(line)) | |
# append to the original line | |
line += (" " * (linelen - len(line) + MARGIN)) | |
line += text | |
print line |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment