Skip to content

Instantly share code, notes, and snippets.

@cesquivias
Last active May 7, 2017 06:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cesquivias/0ecdac66e1def41eb66b47dc461388d0 to your computer and use it in GitHub Desktop.
Save cesquivias/0ecdac66e1def41eb66b47dc461388d0 to your computer and use it in GitHub Desktop.
A simple binary compiler. Converts hexadecimal digits into a binary file. Supports comments
#!/usr/bin/env python
import os.path
import struct
def compile_line(line, i):
no_comment = line.split('#', 1)[0]
hex_code = no_comment.strip().replace(' ', '')
if len(hex_code) % 2 != 0:
raise Exception("%d: hex characters must be in pairs\n%s" % (i, line))
a = [int(hex_code[i:i+2], 16) for i in xrange(0, len(hex_code), 2)]
return bytearray(a)
def main(filename, out_filename):
hxl_file = open(filename, 'r')
bin_file = open(out_filename, 'wb')
for i, line in enumerate(hxl_file):
bin_file.write(compile_line(line, i))
hxl_file.close()
bin_file.close()
if __name__ == '__main__':
import sys
filename = sys.argv[1]
main(filename, sys.argv[2] if len(sys.argv) > 2 else os.path.splitext(filename)[0])
@cesquivias
Copy link
Author

I made this so I could write/modify a binary file without having to use a hex editor. I want to write a JVM class file on the binary level but be able to insert comments between bytes. So I can write a class file as

CAFE BABE # magic
0000 # minor version
0034 # major version
000D # constant pool count

# constant pool
0A00 0300 0A07 000B 0700 0C01 
0006 3C69 6E69 743E 0100 0328 2956 0100 0443 6F64 6501 
000F 4C69 6E65 4E75 6D62 6572 5461 626C 6501 000A 536F 
7572 6365 4669 6C65 0100 0846 6F6F 2E6A 6176 610C 0004 
0005 0100 0346 6F6F 0100 106A 6176 612F 6C61 6E67 2F4F 
626A 6563 7400 21

0002 # this class
0003 # super class
0000 # interface count
0000 # fields count
0001 # methods count

# etc...
00 0100 0400 
0500 0100 0600 0000 1D00 0100 0100 0000 052A B700 01B1 
0000 0001 0007 0000 0006 0001 0000 0001 0001 0008 0000 
0002 0009 C3                    

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment