Skip to content

Instantly share code, notes, and snippets.

@OtterHacker
Last active February 3, 2024 18:42
Show Gist options
  • Save OtterHacker/eebd9aaba18afba395be6e381d0787a7 to your computer and use it in GitHub Desktop.
Save OtterHacker/eebd9aaba18afba395be6e381d0787a7 to your computer and use it in GitHub Desktop.
"""
Transform a binary file into a C header file.
The binary file is splitted into 16 char strings and rebuild at execution time.
The function buildsc() must be called in your main to rebuild the binary file into the sc C variable.
The length is set in the sc_length variable.
Be carefull, try to avoid compiler code optimization as it will remove all these modifications in the final binary.
"""
def bin2c(filename, output_filename):
file = open(filename, 'rb')
binary = file.read()
file.close()
file = open(output_filename, 'w')
i = 1
k = 0
file.write('#define _CRT_SECURE_NO_WARNINGS\n\n')
for j in range(len(binary)):
elt = binary[j]
if(i%16 == 1):
file.write('const char sc_' + format(i//16) + '[16] = {')
k += 1
file.write('{}'.format(hex(elt)))
if(i%16 == 0):
file.write('};\n')
elif j != len(binary) - 1:
file.write(',')
i += 1
if(i%16 != 1):
file.write('};\n')
file.write('\nchar sc[{}];\n'.format(len(binary)))
file.write('int sc_length = {};\n'.format(len(binary)))
file.write("void buildsc_0(){\n")
l = 1
m = 1
for i in range(k):
file.write('\tCopyMemory(&sc[{}], sc_{}, 16);\n'.format(i*16, i))
if(l % 200 == 0):
file.write("}\nvoid buildsc_" + format(m) + "(){\n")
m += 1
l += 1
file.write("}\n")
file.write("void buildsc(){\n")
for i in range(m):
file.write("\tbuildsc_{}();\n".format(i))
file.write("}")
file.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment