利用python代码,将bin文件,指定intel hex格式,转换为hex文件,供jflash烧写

利用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)
  • 5
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值