Skip to content

Instantly share code, notes, and snippets.

@FlyingJester
Created July 19, 2016 00:24
Show Gist options
  • Save FlyingJester/852928bbf76e664444782ae4873b74fb to your computer and use it in GitHub Desktop.
Save FlyingJester/852928bbf76e664444782ae4873b74fb to your computer and use it in GitHub Desktop.
Athena BinToC
from string import Template
import inspect
import os
import sys
import math
autogen_warning = """
/* THIS FILE IS AUTOGENERATED BY:
* tools/athena_bin_to_c.py
* DO NOT EDIT THIS FILE MANUALLY
*/
\n
"""
header_template = Template("""#pragma once
$warning
#include <stdint.h>
#define $size_name $file_size
extern const uint8_t $variable_name [$size_name];
""")
source_template = Template("""$warning
#include \"$header_path\"
const uint8_t $variable_name [$size_name] = {
""")
hex_chars = [
"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"
]
def num_to_hex(n):
if not n:
return "0x00"
if False and n<10:
return str(int(n))
else:
s = ""
prefix = "0x"
if n<16:
prefix = "0x0"
while n:
s = hex_chars[int(n % 16)] + s
n = math.floor(n/16)
return prefix + s
def BinToC(path, outpaths):
for p in outpaths:
thispath = str(p)
if thispath.endswith(".c"):
source_path = thispath
elif thispath.endswith(".h"):
header_path = thispath
variable_name = ""
size_name = ""
for x in os.path.basename(str(path)).lower():
if x.isalpha():
variable_name = variable_name + x
size_name = size_name + x.upper()
elif x.isspace() or x=="_" or x=="-" or x==".":
if variable_name and not variable_name.endswith("_"):
variable_name = variable_name + '_'
if size_name and not size_name.endswith("_"):
size_name = size_name + '_'
elif x.isdigit():
if not variable_name:
variable_name = variable_name + "n"
if not size_name:
size_name = size_name + "N"
variable_name = variable_name + x
size_name = size_name + x
size_name = size_name + "_SIZE"
data = {
"size_name":size_name,
"variable_name":variable_name,
"file_size":str(os.path.getsize(str(path))),
"header_path":os.path.basename(header_path),
"warning":autogen_warning
}
header = open( header_path, "w" )
source = open( source_path, "w" )
infile = open( str(path), "rb" )
header.write(header_template.substitute(data))
source.write(source_template.substitute(data))
i = os.path.getsize(str(path))
z = 0
source.write(" ")
while z != i:
z = z+1
x = infile.read(1)
source.write(num_to_hex(ord(x)) + ", ")
if not z % 16:
source.write("\n ")
source.write("\n};\n")
source.flush()
source.close()
header.flush()
header.close()
if len(sys.argv) < 2:
print("Athena BinToC.\n\tUsage: python BinToC.py [file1] [file2] ...\n")
else:
files = sys.argv[1:]
for input in files:
print("Encoding " + input)
BinToC(input, [input + ".c", input + ".h"])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment