Explorar el Código

增加校验码 大小端

kinve hace 2 años
padre
commit
e0fd188769
Se han modificado 2 ficheros con 15 adiciones y 9 borrados
  1. BIN
      dist/pyChecknum.exe
  2. 15 9
      pyChecknum.py

BIN
dist/pyChecknum.exe


+ 15 - 9
pyChecknum.py

@@ -15,7 +15,7 @@ def intToBytes(value, length):
     return result
 
 #查看文件后的16进制数据
-def ReadBinFile(in_file, type="sum32"):
+def ReadBinFile(in_file, type="sum32", en='little'):
     get_checknum = None
     filename, file_type = os.path.splitext(in_file)  
     out_name = None
@@ -31,9 +31,10 @@ def ReadBinFile(in_file, type="sum32"):
                 checknum += datas[0]
             f.close()
             get_checknum = True
-            checknum_str = '{:08X}'.format(checknum)
+            # checknum_str = '{:08X}'.format(checknum)
+            checknum_bytes = checknum.to_bytes(4, en)    #"little", "big"  # 大端序
+            checknum_str = checknum_bytes.hex()
             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)
@@ -43,8 +44,9 @@ def ReadBinFile(in_file, type="sum32"):
             size =os.path.getsize(in_file)  #获取文件大小
             filedata = f.read()
             checknum = binascii.crc32(filedata)
-            checknum_bytes = intToBytes(checknum, 4)
-            checknum_str = '{:08X}'.format(checknum)
+            checknum_bytes = checknum.to_bytes(4, en)    #"little", "big"  # 大端序
+            # checknum_str = '{:08X}'.format(checknum)
+            checknum_str = checknum_bytes.hex()
             print(in_file, size, "checknum", checknum_str)
             # 输出文件名
             out_name = filename+file_type+".crc32["+checknum_str+"]"
@@ -54,7 +56,7 @@ def ReadBinFile(in_file, type="sum32"):
         # 追加到文件最后
         with open(out_name, "rb+") as f:
             f.seek(0,2)  #位移到最后
-            f.write(bytes(checknum_bytes))
+            f.write(bytes(checknum_bytes)) 
             f.close()
 
 
@@ -62,12 +64,16 @@ 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")
 
     args = parser.parse_args()
     project = str(args.n)
     type = "sum32"      #默认 累加和
-    if str(args.t):
+    en = "little"       #默认 checknum 小端
+    if args.t:
         type = str(args.t)
-
-    ReadBinFile(project, type)
+    if args.e:
+        en = str(args.e)
+    # print(project, type, en)
+    ReadBinFile(project, type, en)