HEX转BIN
- bin_data = bytearray() # 存储BIN文件数据
- current_address = 0 # 当前地址
- for line in hex_file:
- if line[0] != ":": # 忽略非HEX记录
- continue
- length = int(line[1:3], 16)
- address = int(line[3:7], 16)
- record_type = int(line[7:9], 16)
- data = line[9:9+2*length]
- checksum = int(line[9+2*length:9+2*length+2], 16)
- if record_type == 0x00: # 数据记录
- bin_data[address:address+length] = bytes.fromhex(data)
- elif record_type == 0x04: # 扩展线性地址记录
- current_address = int(data, 16) << 16
- elif record_type == 0x01: # 文件结束记录
- break
BIN转HEX
- def bin_to_hex(bin_data, start_address=0x0000):
- hex_lines = []
- length = 16 # 每行16字节
- for i in range(0, len(bin_data), length):
- data = bin_data[i:i+length]
- address = start_address + i
- record = f":{length:02X}{address:04X}00{data.hex().upper()}"
- checksum = calculate_checksum(record)
- hex_lines.append(f"{record}{checksum:02X}")
- hex_lines.append(":00000001FF") # 文件结束记录
- return "\n".join(hex_lines)
HEX文件包含地址、数据和校验信息,适合存储复杂的内存布局。
BIN文件是纯二进制数据,适合直接烧录到单片机的Flash中。
转换的核心是提取HEX文件中的数据并按地址写入BIN文件,或者为BIN文件添加地址信息并生成HEX文件。
|