Skip to content

Instantly share code, notes, and snippets.

@hanasuru
Last active January 24, 2025 05:55
Show Gist options
  • Save hanasuru/d3c39a0f2f55d45f9bca0860836a50c7 to your computer and use it in GitHub Desktop.
Save hanasuru/d3c39a0f2f55d45f9bca0860836a50c7 to your computer and use it in GitHub Desktop.
Reverse octal-dump
#!/usr/bin/env python
from __future__ import unicode_literals
from __future__ import division
import struct
import sys
import re
RULE = re.compile(r'(\d{7,})((\s?\d{6}){0,8})')
class ROD(object):
def __init__(self, lines):
self._lines = lines
self._ascii = self.decode(lines)
def decode(self, lines):
plain_text = bytearray()
repeat = False
repeated_offsets = None
repeated_bytes = None
offsets = None
for line in lines:
match = RULE.match(line)
if match:
offsets = int(match.group(1), 8)
bytestr = match.group(2).split()
if repeat:
count = (offsets - repeated_offsets) // 16 - 1
plain_text.extend(self.process_bytes(repeated_bytes, count))
plain_text.extend(self.process_bytes(bytestr))
repeat = False
elif '*' in line:
repeat = True
repeated_bytes = bytestr
repeated_offsets = offsets
if offsets and offsets % 2:
plain_text = plain_text[:-1]
return plain_text
def process_bytes(self, bytestr, count=1):
result = bytearray()
for byte in bytestr:
byte = int(byte, 8)
result.extend(struct.pack('<H', byte))
return result * count
@property
def ascii(self):
return self._ascii
if __name__ == "__main__":
if len(sys.argv) > 1:
with open(sys.argv[1], 'r') as f:
lines = f.readlines()
else:
lines = sys.stdin.readlines()
rod = ROD(lines)
try:
sys.stdout.write(rod.ascii)
except:
sys.stdout.buffer.write(rod.ascii)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment