#!/usr/bin/env python # -*- coding: utf-8 -*- import os import shutil import argparse import struct import binascii def intToBytes(value, length): result = [] for i in range(0, length): result.append(value >> (i * 8) & 0xff) result.reverse() return result #查看文件后的16进制数据 def ReadBinFile(in_file, type="sum32"): get_checknum = None filename, file_type = os.path.splitext(in_file) out_name = None checknum_bytes = None # 方式一:累加和 if type == "sum32": with open(in_file, "rb") as f: #二进制打开文件 size =os.path.getsize(in_file) #获取文件大小 checknum = 0 for i in range(size): datas = f.read(1) checknum += datas[0] f.close() get_checknum = True checknum_str = '{:08X}'.format(checknum) print(in_file, size, "checknum", checknum_str) checknum_bytes = intToBytes(checknum, 4) # 输出文件名 out_name = filename+file_type+".sum32["+checknum_str+"]" shutil.copyfile(in_file, out_name) elif type == "crc32": # 方式2:crc32 with open(in_file, "rb") as f: #二进制打开文件 size =os.path.getsize(in_file) #获取文件大小 filedata = f.read() checknum = binascii.crc32(filedata) checknum_bytes = intToBytes(checknum, 4) checknum_str = '{:08X}'.format(checknum) print(in_file, size, "checknum", checknum_str) # 输出文件名 out_name = filename+file_type+".crc32["+checknum_str+"]" shutil.copyfile(in_file, out_name) if out_name: # 追加到文件最后 with open(out_name, "rb+") as f: f.seek(0,2) #位移到最后 f.write(bytes(checknum_bytes)) f.close() if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("n", help="bin文件名,譬如 COAB21232D.bin") parser.add_argument("-t", help="校验方式:sum32,crc32, 默认sum32") args = parser.parse_args() project = str(args.n) type = "sum32" #默认 累加和 if str(args.t): type = str(args.t) ReadBinFile(project, type)