Python converts hex file to bin file

Python Converts Hex Files to Bins

Demand Background

The remote control of the MiniFly vehicle has IAP function. The APP code must be downloaded at an offset of 9K bytes, so before downloading the APP code, download the BootLoader code to the starting position 0x08000000, and then offset the position of 9K bytes to download the APP code. I want to write the BootLoader bin file directly to the Flash location in the APP. So you need to look at the specific contents of the bin file generated by the BootLoader code and then use the

static const uint8_t bootload_src[]__attribute__((at(0x08000000)))=
{
//Specific contents of bin file
}

Write Flash to the specified location

However, the binviewer on the Internet and the files that can open bins are all garbled. The bins converted from hex2bin files are also garbled, so we have to understand the relationship between hex files and bins.

The most critical thing about hex files is where the data is written, so in theory, extracting the data from the bin s in Hex is all that matters.

HEX file format

The general Hex file record format is as follows

:[1 byte length][2 byte address][1 byte record type][n byte data segment][1 byte checksum]

  • : (colon) Each Intel HEX record starts with a colon;
  • The data length field, which represents the number of data bytes (dds) in the record;
  • Address field, which represents the starting address of the data in the record;
    • 00 - Data Record
    • 01 - End of FileRecord
    • 02 - Extended Segment Address Record
    • 03 - Start Segment Address Record
    • 04 - Extended Linear Address Record
    • 05 - Begin linear address recording (Extended Segment Address Record)
  • Data field, which represents one byte of data. A record can have many data bytes. The number of data bytes in a record must match the number specified in the data length field (ll).
  • Checksum field, which represents the checksum of this record. Checksum is calculated by adding the values of all hexadecimal encoded number pairs in the record to 256 modulus to make the following supplement.

code implementation

import sys
#hex file format
#[1 Byte Length][2 Byte Address][1 Byte Record Type][n Byte Data Segment][1 Byte Checksum]
def GetBin(src_name,dst_file):
    print("data will be save to :"+dst_file)
    print("data from :"+src_name)

    src = open(src_name,'r')                #Open Read-Only
    dst = open(dst_file,"w+")               #Save by Append

    dst.write("static const unsigned int src_bootload[]__attrbute__((at(0x08000000))) = {\n")

    while(True):
        str_file = src.readline()
        data_len = (int)(len(str_file))
        if not str_file:
            break
        #print(str_file[8])                 #str_file[8] represents the type of data
        if (int(str_file[8]) != 0):        #Remove data independent of bin data
            continue

        str_file = str_file[9:(data_len-3)] #Remove length, address, type, and checks
        list_file = list(str_file)          #Convert string data to a list for easy insertion
        for i in range(1,((data_len-3)-9)//2+1): #Insert after', '
            list_file.insert(2*i+(i-1),",") #The I of 2*i denotes the preceding number of bytes (2: one byte, two numbers), and i-1 denotes the preceding commas
        str_file = ''.join(list_file)       #Convert the list of inserted data to a string again

        list_file = list(str_file)          #Insert 0x after inserting a comma
        for i in range(0,((data_len-3)-9)//2): #Insert'0x'before
            list_file.insert(2*i+2*i,"0x")  #The first i represents the number of bytes preceding it, and the second i represents the number of 0x
        str_file = ''.join(list_file)       #Convert the list of inserted data to a string again

        dst.write('    '+str_file)             #Save data and join carriage return after processing a row of data
        dst.write("\n")

    dst.write("}")
    src.close()
    dst.close()

def main():
    src_filename = sys.argv[1]
    dst_filename = sys.argv[2]

    GetBin(src_filename,dst_filename)

if __name__ == "__main__":
    if(len(sys.argv) != 3):
        print("para error\r\n")
        exit()
    main()

Usage method

  • The first thing to do is to have a Python environment

  • Execute the following commands in the command window

    python D:\DeskTop\hex2bin.py D:\DeskTop\Bootloader_F103.hex .\bin.bin

    • D:\DeskTop\hex2bin.py is the path to hex2bin.py
    • D:\DeskTop\Bootloader_F103.hex means Bootloader_ The path to the hex file F103.hex will convert
    • \bin.bin is the file name to be generated and the path to the suffix
  • The easiest way is to type python in the command window, drag hex2bin.py into the command window, drag the hex file you want to convert into the command window, and then type the name of the generated file.

Keywords: Python Back-end

Added by myaion on Mon, 06 Dec 2021 20:44:50 +0200