| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485 |
- #!/usr/bin/env python
- # -*- coding: utf-8 -*-
- import os
- import shutil
- import argparse
- import binascii
- def calChecknum(type="sum32", datas=[]):
- if type == "sum32":
- return sum(datas)
- elif type == "crc32":
- return binascii.crc32(datas)
- else:
- print("unKown type: "+type)
- return datas
-
- #查看文件后的16进制数据
- def ReadBinFile(in_file, type="sum32", en='little', block_size=1024):
- filename, file_type = os.path.splitext(in_file)
- checknum_bytes = None
- out_name0 = filename+file_type+"."+type
- f = open(in_file, "rb")
- o = open(out_name0, "wb+")
- if f and o: #二进制打开文件
- # 1.计算和写入分片校验码
- if block_size:
- while True:
- # 读一块
- datas = f.read(block_size)
- if len(datas) == 0:
- break
- # 这一块的checknum
- checknum = calChecknum(type, datas)
- checknum_bytes = checknum.to_bytes(4, en) #"little", "big" # 大端序
- # 写入数据和checknum
- o.seek(0,2) #位移到最后 SEEK_END(值为2) SEEK_CUR(值为1) SEEK_SET(值为0)
- o.write(datas)
- o.write(bytes(checknum_bytes))
- else:
- shutil.copy(in_file, out_name0)
- # 2.计算原始文件校验码
- f.seek(0,0)
- datas = f.read()
- checknum_all = calChecknum(type, datas)
- f.close()
- o.close()
- # 3.写入原始文件校验码
- checknum_all_bytes = checknum_all.to_bytes(4, en) #"little", "big" # 大端序
- print(in_file, os.path.getsize(in_file), type, checknum_all_bytes.hex())
- # 输出文件名
- out_name1 = filename+file_type+"."+type+"["+checknum_all_bytes.hex()+"]"
- shutil.move(out_name0, out_name1)
- # 追加到文件最后
- with open(out_name1, "rb+") as f:
- f.seek(0,2) #位移到最后 SEEK_END(值为2) SEEK_CUR(值为1) SEEK_SET(值为0)
- f.write(bytes(checknum_all_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")
- parser.add_argument("-e", help="校验码大小端:little,big, 默认little")
- parser.add_argument("-s", help="分块大小:0,1024,2048, 默认0不分块")
- args = parser.parse_args()
- project = str(args.n)
- type = "sum32" #默认 累加和
- en = "little" #默认 checknum 小端
- block_size = 0 #默认 0
- if args.t:
- type = str(args.t)
- if args.e:
- en = str(args.e)
- if args.s:
- block_size = int(args.s)
- # print(project, type, en)
- ReadBinFile(project, type, en, block_size)
|