Files

73 lines
2.6 KiB
Python
Executable File

#!/usr/bin/env python3
import argparse
import os
import glob
from datetime import datetime
def convert_bin_to_c(bin_file, output_dir):
# Read the bin file
with open(bin_file, 'rb') as f:
bin_data = f.read()
# Get the length of the bin file
bin_len = len(bin_data)
# Set the output file path within the specified directory
output_file = os.path.join(output_dir, 'cx9261a_riscv_bin.c')
with open(output_file, 'w') as f:
# Write metadata comments
f.write(f'// Generated C code array\n')
f.write(f'// Date: {datetime.now().strftime("%Y-%m-%d %H:%M:%S")}\n')
f.write(f'// Source file: {os.path.basename(bin_file)}\n\n')
# Write headers and data length
f.write('#include <stdint.h>\n')
f.write('#include "cx9261adriver_c.h"\n\n')
f.write(f'uint32_t CX9261A_RiscvBinLen = {bin_len};\n')
f.write(f'uint8_t *CX9261A_RiscvBin = (uint8_t[]){{\n\t')
# Write data as hex values in the array
for i, byte in enumerate(bin_data):
f.write(f'0x{byte:02X}, ')
# Add a newline every 12 bytes
if (i + 1) % 12 == 0:
f.write('\n\t')
# Add a newline if the last line has fewer than 12 bytes
if bin_len % 12 != 0:
f.write('\n')
# End the array
f.write('};\n')
print(f"Generated C file: {output_file}")
if __name__ == "__main__":
# Set up command line argument parsing
parser = argparse.ArgumentParser(description="Convert a CX9261A Riscv bin file to a C code array.")
parser.add_argument("bin_file", type=str, nargs='?', help="Path to the bin file (optional)")
parser.add_argument("-o", "--output_dir", type=str, default=".", help="Output directory (default is the current directory)")
# Parse arguments
args = parser.parse_args()
# If no bin file is provided, search for a .bin file in the current directory
if args.bin_file is None:
bin_files = glob.glob("*.bin")
if len(bin_files) == 0:
print("Error: No .bin file found in the current directory.")
exit(1)
elif len(bin_files) > 1:
print("Error: Multiple .bin files found in the current directory. Specify one as an argument.")
exit(1)
else:
args.bin_file = bin_files[0]
# Check if output directory exists, create if not
if not os.path.isdir(args.output_dir):
os.makedirs(args.output_dir)
# Perform the conversion
convert_bin_to_c(args.bin_file, args.output_dir)