利用python代码,将bin文件,指定intel hex格式,转换为hex文件,供jflash烧写;
完整的工程包括 先合并bin文件,再将合并之后的bin文件转换为hex文件;
请参考链接python将bin文件合并之后再打包为hex文件
def to_hex_string(byte):
return '{:02X}'.format(byte)
def calculate_checksum(record):
total = sum(record)
return ((~total + 1) & 0xFF)
# 把bin文件根据intel hex文件格式(keil编译的),转换为hex文件
def convert_bin_to_hex(bin_file, hex_file, start_address):
with open(bin_file, 'rb') as bin_f:
bin_data = bin_f.read()
hex_records = []
address = start_address
current_segment = (address >> 16) & 0xFFFF # 初始化当前段地址
# 添加第一行扩展线性地址记录
record = [0x02, 0x00, 0x00, 0x04, (current_segment >> 8) & 0xFF, current_segment & 0xFF]
checksum = calculate_checksum(record)
record.append(checksum)
hex_record = ':' + ''.join(to_hex_string(byte) for byte in record)
hex_records.append(hex_record)
for i in range(0, len(bin_data), 32):
# 当前段地址
segment = (address >> 16) & 0xFFFF
if segment != current_segment:
# 如果段地址变化,添加扩展线性地址记录
current_segment = segment
record = [0x02, 0x00, 0x00, 0x04, (segment >> 8) & 0xFF, segment & 0xFF]
checksum = calculate_checksum(record)
record.append(checksum)
hex_record = ':' + ''.join(to_hex_string(byte) for byte in record)
hex_records.append(hex_record)
chunk = bin_data[i:i+32]
length = len(chunk)
record = [length, (address >> 8) & 0xFF, address & 0xFF, 0x00] + list(chunk)
checksum = calculate_checksum(record)
record.append(checksum)
hex_record = ':' + ''.join(to_hex_string(byte) for byte in record)
hex_records.append(hex_record)
address += length
hex_records.append(':00000001FF') # End of file record
with open(hex_file, 'w') as hex_f:
hex_f.write('\n'.join(hex_records) + '\n')
print("convert_bin_to_hex ok")
# 4-指定起始地址,将all.bin文件转换为all.hex文件
output_bin_file = 'mcu_all.bin'
output_hex_file = 'mcu_all.hex'
start_address = 0x08000000 # 指定MCU的flash起始地址
convert_bin_to_hex(output_bin_file, output_hex_file, start_address)