-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconvert_binary_to_c_header.py
More file actions
99 lines (74 loc) · 2.35 KB
/
convert_binary_to_c_header.py
File metadata and controls
99 lines (74 loc) · 2.35 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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
# Copyright 2025 NXP
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
import datetime
import os
import sys
SUCCESS = 0
ERROR = 1
OUT_FILENAME = "edgelock_firmware.h"
HEADER_GUARD = "__EDGELOCK_FIRMWARE_H__"
ARRAY_NAME = "edgelock_fw"
HELPTEXT = f"""
Script for converting a firmware binary to a C header file with an array
representation of the binary.
Usage: python {sys.argv[0]} [-h|--help] FIRMWARE_BINARY_FILE
The output is placed (or overwritten) to an `{OUT_FILENAME}` file
in the same directory, in which this script was run.
The script takes one required argument; a path to the binary firmware file.
"""
def show_help():
print(HELPTEXT, end='')
def main():
if ("--help" in sys.argv) or ("-h" in sys.argv):
show_help()
return SUCCESS
if (len(sys.argv) < 2):
print("Error: binary filename is missing", file=sys.stderr)
return ERROR
# Strip filename from path
image_filename_full = sys.argv[1]
[_, image_filename] = os.path.split(image_filename_full)
header_text = f'EdgeLock Firmware ({image_filename})'
with open(image_filename_full, 'rb') as file:
binary_data = file.read()
# Split the data into bytes represented as strings
# with 12 Bytes per string
tmp_separator = ' '
hex_str = binary_data.hex(tmp_separator, -12)
split_str = hex_str.split(' ')
# Construct the C array with correct formatting
str_final = "\n"
for s in split_str:
l = len(s)
tmp = 'u, 0x'.join(s[i:i+2] for i in range(0, l, 2))
str_final += (' 0x' + tmp + 'u,\n')
with open(OUT_FILENAME, 'w') as file:
# Header
file.write(f"""/**
* Copyright {datetime.datetime.now().year} NXP
* All rights reserved.
*
* SPDX-License-Identifier: BSD-3-Clause
*
*
* This file was generated by a script.
*/
/*******************************************************************************
*""")
file.write(f' {header_text}')
file.write(f"""
******************************************************************************/
#ifndef {HEADER_GUARD}
#define {HEADER_GUARD}
const uint8_t {ARRAY_NAME}[] = {{""")
# The FW data
file.write(str_final)
# Footer
file.write(f"""}};
#endif /* {HEADER_GUARD} */
""")
return SUCCESS
if __name__ == "__main__":
main()