-
Notifications
You must be signed in to change notification settings - Fork 43
Expand file tree
/
Copy pathconvert_binary_to_array.py
More file actions
47 lines (38 loc) · 1.98 KB
/
convert_binary_to_array.py
File metadata and controls
47 lines (38 loc) · 1.98 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# convert_binary_to_array.py
import sys
from pathlib import Path
def binary_to_c_array(bin_file, array_name, size_BeforeCompression, compression_activated):
with open(bin_file, 'rb') as f:
binary_data = f.read()
hex_array = ', '.join(f'0x{b:02x}' for b in binary_data)
c_array = f'const unsigned char {array_name}[] = {{\n {hex_array}\n}};\n'
c_array += f'const size_t {array_name}_size = sizeof({array_name}); // {len(binary_data)}\n'
c_array += f'const size_t {array_name}_size_uncompressed = '
if compression_activated:
c_array += f'{size_BeforeCompression}; // size of the data in bytes, once it has been uncompressed.\n'
else:
c_array += f'{array_name}_size; // same than raw buffer, because data is not compressed.\n'
c_array += f'const bool {array_name}_isCompressed = '
if compression_activated:
c_array += f'true;\n'
else:
c_array += f'false;\n'
return c_array
if __name__ == "__main__":
if len(sys.argv) != 5:
print(f"Usage: {sys.argv[0]} <input_binary_file_before_compression> <input_binary_file_after_compression> <output_header_file> <compression_activated>")
sys.exit(1)
bin_file_beforeCompression = sys.argv[1]
bin_file_afterCompression = sys.argv[2] # not used if 'compression_activated' is OFF
header_file_path = sys.argv[3]
compression_activated = sys.argv[4].lower() == "on" # sys.argv[4] should be "ON" or "OFF"
header_file = Path(header_file_path).name
array_name = header_file.replace('.', '_')
if not compression_activated:
bin_file_afterCompression = bin_file_beforeCompression
c_array = binary_to_c_array(bin_file_afterCompression, array_name, Path(bin_file_beforeCompression).stat().st_size, compression_activated )
with open(header_file_path, 'w') as f:
f.write("// generated by convert_binary_to_array.py\n")
if compression_activated:
f.write(f"// Data is compressed.\n")
f.write(c_array)