第一篇博客将HEX文件成功转成了bin文件,这篇博客在前面的代码上对Bin文件进行处理,
计算bin文件的CRC值和Hash值
第一步导入hashlib库和crc库在导入库之前确保你已经安装了这两个包。
import hashlib
import crcmod
class HEX_BIN(object):
def TRANS(self,File_path_hex,File_path_bin):
ih = IntelHex()
ih.fromfile(File_path_hex, format='hex')
binary_data = ih.tobinarray()
with open(File_path_bin, 'wb') as bin_file:
bin_file.write(bytes(binary_data))
#print(binary_data)
def CRC_XML(self,File_path_bin,file_path_xml):
# 创建一个 CRC 模块
crc32_func = crcmod.mkCrcFun(0x104c11db7, initCrc=0xFFFFFFFF, xorOut=0xFFFFFFFF)
# 从二进制文件加载数据
with open(File_path_bin, 'rb') as bin_file:
binary_data = bin_file.read()
# 计算 CRC 值
crc_value = crc32_func(binary_data)
# 输出 CRC 值
#print(f"CRC32 Value: {hex(crc_value)}")
# 创建 XML 元素
root = ET.Element("CRCData")
crc_element = ET.SubElement(root, "CRC32")
crc_element.text = hex(crc_value)
# 创建 XML 对象
tree = ET.ElementTree(root)
# 保存 XML 文件
tree.write(file_path_xml)
def BIN_HASH(self,file_path_bin,file_path_hash,hash_algorithm):
# 选择哈希算法
hash_function = hashlib.new(hash_algorithm)
# 以二进制方式打开文件并逐块更新哈希值
with open(file_path_bin, 'rb') as file:
block_size = 65536 # 64 KB
file_block = file.read(block_size)
while len(file_block) > 0:
hash_function.update(file_block)
file_block = file.read(block_size)
with open(file_path_hash, 'w') as hash_file:
hash_file.write(hash_function.hexdigest())
# 返回十六进制表示的哈希值
# return hash_function.hexdigest()
if __name__=="__main__":
#本地的hex文件地址
file_path_hex= 'C:\\Users\\Administrator\\Desktop\\12345\\1.hex'
#想要保存的Bin文件地址
file_path_bin= 'C:\\Users\\Administrator\\Desktop\\12345\\1.bin'
file_path_xml= 'C:\\Users\\Administrator\\Desktop\\12345\\1.xml'
file_path_hash = 'C:\\Users\\Administrator\\Desktop\\12345\\hash.txt'
hash_algorithm = 'sha256'
U = HEX_BIN()
U.TRANS(file_path_hex,file_path_bin)
U.CRC_XML(file_path_bin,file_path_xml)
U.BIN_HASH(file_path_bin,file_path_hash,hash_algorithm)
运行上诉代码可以发现,在本地文件夹12345中生成了3个文件。