Skip to content

Instantly share code, notes, and snippets.

@apkunpacker
Forked from OtterHacker/bin2c.py
Created October 30, 2022 02:16
Show Gist options
  • Save apkunpacker/4ae4a71ab97e4788980d7edc7572e0ba to your computer and use it in GitHub Desktop.
Save apkunpacker/4ae4a71ab97e4788980d7edc7572e0ba 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 = 1
file.write('#define _CRT_SECURE_NO_WARNINGS\n\n')
file.write('char sc_0[16] = {')
for j in range(len(binary)):
elt = binary[j]
file.write('{}'.format(hex(elt)))
if(i%16 == 0):
file.write('};\nconst char sc_' + format(i//16) + '[16] = {')
k += 1
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))
# file.write('\tfor (int i = 0; i < 16; i++) {sc[' + format(i*16) +' + i] = sc_' + format(i) + '[i];}\n')
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