Fix style and code issues in bin2carray python script

This commit is contained in:
Mario Hüttel 2023-06-23 22:43:45 +02:00
parent 0c8a0cd562
commit c6038969ca

View File

@ -1,35 +1,45 @@
#!env python #!env python
# Convert a file to a c array """
# bin2carray <output file> <input file> Convert a file to a c array
bin2carray <output file> <input file>
"""
import os import os
import os.path import os.path
import sys import sys
if len(sys.argv) < 3: def main():
sys.exit(-1) """
Main script function
"""
if len(sys.argv) < 3:
return -1
source_file = sys.argv[2] source_file = sys.argv[2]
dest_file = sys.argv[1] dest_file = sys.argv[1]
print("%s --> %s" % (source_file, dest_file)) print(f'{source_file} --> {dest_file}')
with open(source_file, "rb") as src: with open(source_file, 'rb') as src:
data = src.read() data = src.read()
with open(dest_file, "w") as dest: with open(dest_file, 'w', encoding='utf-8') as dest:
header_guard = "__" + os.path.basename(dest_file).replace('.', '_').replace('-', '_') + "_H__" header_guard = '_' + os.path.basename(dest_file).replace('.', '_').replace('-', '_') + '_H_'
dest.write("#ifndef %s\n" % (header_guard)) header_guard = header_guard.upper()
dest.write("#define %s\n" % (header_guard)) dest.write(f'#ifndef {header_guard}\n')
dest.write("static const char binary_blob[%d] = {\n" % (len(data))) dest.write(f'#define {header_guard}\n')
for current,idx in zip(data, range(len(data))): dest.write(f'static const char binary_blob[{len(data)}] = {{\n')
if ((idx+1) % 4 == 0): for idx, current in enumerate(data, start=1):
dest.write(hex(current)+",\n") if idx % 4 == 0:
else: dest.write(hex(current)+',\n')
dest.write(hex(current)+",") else:
dest.write(hex(current)+',')
dest.write("};\n") dest.write('};\n')
dest.write("#endif /* %s */\n" % (header_guard)) dest.write(f'#endif /* {header_guard} */\n')
sys.exit(0) return 0
if __name__ == '__main__':
sys.exit(main())