Python之bin2c

使用Python将bin文件转为c语言数组:

import os
import sys
import time

FILE=sys.argv[1]
(filename,ext) = os.path.splitext(FILE)
file_to_write = filename+'.c'

def bin2c():
    with open(FILE, 'rb') as fp_read:
        cnt = 0
        fp_write = open(file_to_write, 'w')
        fp_write.write('const unsigned char bin2c[] = {\n')
        while 1:
            cont = fp_read.read(1)
            if len(cont) > 0:
                tmp=int(ord(cont))
                cnt = cnt + 1
                #print("0x%02X" % tmp, end='')
                fp_write.write("0x%02X," % tmp)
                if cnt % 8 == 0:
                    #print()
                    fp_write.write('\n')
                else:
                    #print(end=' ')
                    fp_write.write(' ')
            else:
                fsize = os.path.getsize(FILE)
                if cnt == fsize:
                    print("Success!")
                else:
                    print("Failed!")
                break
        fp_write.write('\n};')
        fp_write.close()

bin2c()
time.sleep(1)
#os.system("pause")

将bin文件拖拽到bin2c.py上或使用bat批处理执行带参数的python脚本即可得到同名的.c文件(c语言数组)

猜你喜欢

转载自blog.csdn.net/u011958166/article/details/78672562