https://github.com/python-intelhex/intelhex/tree/f3db028f40aa9e108dc24241b57c3a5213751a44
首先安装库: pip install intelhex。 不要用conda安装,可能装不上。
下载 bin2hex.py和hex2bin.py。
需要转成bin时: python hex2bin.py in.hex out.bin。
需要转成hex时:python bin2hex.py in.bin out.hex。
例子: 烧录文件hex,需要从大端转成小端。过程如下:
1. python hex2bin.py in.hex out.bin //hex文件转成bin
2. python msb2lsb.py -i out.bin -o lsb.bin //大端转成小端
3. python bin2hex.py lsb.bin out.hex //已把in.hex转成小端的out.hex文件了。
msb2lsb.py 代码如下:
#!/usr/bin/env python # --coding:utf-8 import sys import getopt import os import socket import struct def Reverse8Bit_ver0(b): b = (b >> 4) | (b << 4) b = ((b & 0xcc) >> 2) | ((b & 0x33) << 2) return ((b & 0xaa) >> 1) | ((b & 0x55) << 1) def Reverse8Bit(a): b = a b = (b & 0x55) << 1 | (b & 0xaa) >> 1 b = (b & 0x33) << 2 | (b & 0xcc) >> 2 b = (b & 0x0f) << 4 | (b & 0xf0) >> 4 return b def Reverse32Bit(a): b = a b = (b & 0x55555555) << 1 | (b & 0xaaaaaaaa) >> 1 b = (b & 0x33333333) << 2 | (b & 0xcccccccc) >> 2 b = (b & 0x0f0f0f0f) << 4 | (b & 0xf0f0f0f0) >> 4 b = (b & 0x00ff00ff) << 8 | (b & 0xff00ff00) >> 8 b = (b & 0x0000ffff) << 16 | (b & 0xffff0000) >> 16 return b def Msb2Lsb4File(in_file_name, out_file_name): src = open(in_file_name, 'rb') size = os.path.getsize(in_file_name) out = open(out_file_name, 'wb') for i in range(size): chunk = src.read(1) b = Reverse8Bit(chunk[0]) out.write(b.to_bytes(1, byteorder='little', signed=False)) src.close() out.close() def Big_little_endian(in_file_name, out_file_name): src = open(in_file_name, 'rb') size = os.path.getsize(in_file_name) out = open(out_file_name, 'wb') for i in range(size): chunk = src.read(4) s = int.from_bytes(chunk, byteorder="big") ps = struct.pack('<I', s) out.write(ps) src.close() out.close() def main(argv): inputfile = '' outputfile = '' batfile = '' try: opts, args = getopt.getopt(argv, "hi:o:e:", ["ifile=", "ofile=", "efile="]) except getopt.GetoptError: print('byte_reverse.py -i <inputfile> -o <outputfile> -e <batfile>') sys.exit(2) for opt, arg in opts: if opt == '-h': print('byte_reverse.py -i <inputfile> -o <outputfile> -e <batfile>') sys.exit() elif opt in ("-i", "--ifile"): inputfile = arg elif opt in ("-o", "--ofile"): outputfile = arg elif opt in ("-e", "--efile"): batfile = arg print('输入的文件为:', inputfile) print('输出的文件为:', outputfile) print('bat的文件为:', batfile) Msb2Lsb4File(inputfile, outputfile) # os.system(batfile) if __name__ == '__main__': main(sys.argv[1:])