python-处理程序后的脚本hex-bin

# -*- coding: utf-8 -*-
"""
Created on Fri Apr  3 10:42:03 2020

@author: wangpin
"""

import sys,os
from intelhex import hex2bin
import getopt

def func_hex2bin():
    '''convert hex to bin'''
    
    hex2bin('./temp/stm32_app.hex', './stm32_app.bin');
    hex2bin('./temp/stm32_res1.hex', './stm32_res1.bin');
    hex2bin('./temp/stm32_res2.hex', './stm32_res2.bin');
    
    
def func_hex_split():
    '''split hex file according address:0x08000000, 0x60000000, 0x64000000'''
    
    print("File convert...")
    
    if not os.path.exists("./temp"):
        os.makedirs("temp")
    try:
        hexf = open("application.hex", 'rb')
        hexTarget = open("./temp/stm32_app.hex", 'wb')
        hexRes1 = open("./temp/stm32_res1.hex", 'wb')
        hexRes2 = open("./temp/stm32_res2.hex", 'wb')
    except:
        print("file create failed!")
        sys.exit()
    else:
        RES1_ADDR  = 0X60000000
        RES2_ADDR  = 0X64000000
        
        hexData = hexf.readlines()
        
        # : LL aaaa TT D..D CC
        # TT:
        # 0X00: Data Record         ----
        # 0x01: End of fileRecord   ----
        # 0x02: 扩展地址
        # 0x03: 开始段地址记录
        # 0x04: 扩展线性地址记录    ---
        # 0x05: 开始线性地址记录
        gDataAddrBase = 0
        
        for x in hexData:
            dataSize = int(x[1:3], 16)
            dataOff  = int(x[3:7], 16)
            dataType = int(x[7:9], 16)
            if dataType == 0x04:
                '''地址'''
                gDataAddrBase = int(x[9:13],16)*pow(2,16)
                
                if gDataAddrBase >= RES2_ADDR:
                    hexRes2.write(x)
                elif gDataAddrBase >= RES1_ADDR:
                    hexRes1.write(x)
                else:
                    hexTarget.write(x)
                
            elif dataType == 0x00:
                '''数据'''
                if gDataAddrBase >= RES2_ADDR:
                    hexRes2.write(x)
                elif gDataAddrBase >= RES1_ADDR:
                    hexRes1.write(x)
                else:
                    hexTarget.write(x)
                    
            elif dataType == 0x01:
                '''文件结束'''
                hexRes2.write(x)
                hexRes1.write(x)
                hexTarget.write(x)
            else:
                hexRes2.write(x)
                hexRes1.write(x)
                hexTarget.write(x)

if __name__ == '__main__':
    
    func_hex_split()
    func_hex2bin()

 

你可能感兴趣的:(python-处理程序后的脚本hex-bin)