[feat] add binary_to_c_array
This commit is contained in:
parent
4885f2a423
commit
807a79f19c
48
python/binary_to_c_array/binary_to_c_array.py
Normal file
48
python/binary_to_c_array/binary_to_c_array.py
Normal file
@ -0,0 +1,48 @@
|
|||||||
|
import sys
|
||||||
|
|
||||||
|
def binary_to_c_array(binary_file_path, c_array_name, output_c_file):
|
||||||
|
# 读取二进制文件
|
||||||
|
with open(binary_file_path, "rb") as file:
|
||||||
|
binary_data = file.read()
|
||||||
|
|
||||||
|
# 获取数组长度
|
||||||
|
array_length = len(binary_data)
|
||||||
|
|
||||||
|
# 初始化C数组字符串
|
||||||
|
c_array = "const unsigned char " + c_array_name + "[" + str(array_length) + "] = {\n "
|
||||||
|
|
||||||
|
# 用于记录当前的偏移地址
|
||||||
|
offset = 0
|
||||||
|
|
||||||
|
# 将二进制数据转换为C数组格式
|
||||||
|
for i, byte in enumerate(binary_data):
|
||||||
|
# 每16个字节换行
|
||||||
|
if i % 16 == 0 and i > 0:
|
||||||
|
c_array += "/* Offset: {:#08x} */\n ".format(offset)
|
||||||
|
offset += 16
|
||||||
|
c_array += "0x{:02X}, ".format(byte)
|
||||||
|
c_array += "/* Offset: {:#08x} */\n".format(offset)
|
||||||
|
|
||||||
|
# 去掉最后一个逗号和空格
|
||||||
|
# c_array = c_array.rstrip(", ")
|
||||||
|
|
||||||
|
# 结束数组定义
|
||||||
|
c_array += "};\n"
|
||||||
|
|
||||||
|
# 写入到C文件
|
||||||
|
with open(output_c_file, "w") as c_file:
|
||||||
|
c_file.write(c_array)
|
||||||
|
|
||||||
|
# 检查命令行参数数量
|
||||||
|
if len(sys.argv) != 4:
|
||||||
|
print("Usage: python script.py <binary_file_path> <c_array_name> <output_c_file>")
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
# 从命令行参数获取输入
|
||||||
|
binary_file_path = sys.argv[1]
|
||||||
|
c_array_name = sys.argv[2]
|
||||||
|
output_c_file = sys.argv[3]
|
||||||
|
|
||||||
|
# 转换二进制文件并保存为C数组
|
||||||
|
binary_to_c_array(binary_file_path, c_array_name, output_c_file)
|
||||||
|
print(f"C array has been written to {output_c_file}")
|
||||||
Loading…
Reference in New Issue
Block a user