python计算二进制bin文件hash值

一 hash的价值

  hash值的唯一性仅仅在是同一个文件的情况下得到了同样的hash值,而哪怕错误一个字节也会得到不一样的hash值。

 hash值得最大价值就是唯一性。这样在bin文件检查和校验这块用处非常大,做嵌入式的,经常会遇到版本无法找到情况,利用hash来查找bin文件是否一致,非常方便。

二 实例分析

  python以简洁著称,下面给出一个python的例子:

import os
import argparse
import hashlib

def check_file_hash(bin_file):
    f = open(bin_file,"rb")
    thehash = hashlib.md5()
    theline = f.readline()

    while(theline):
        thehash.update(theline)
        theline = f.readline()

    return thehash.hexdigest()


def get_parser():
    parser = argparse.ArgumentParser(description='change extension of files in a working directory')
    parser.add_argument('bin_file', metavar='BIN_FILE', type=str, nargs=1,
                        help='the directory where to change extension')
    return parser

def main():
    parser = get_parser()
    args = vars(parser.parse_args())

    bin_file = args['bin_file'][0]

    hash_value = check_file_hash(bin_file)
    print("hash_value",hash_value)

if __name__=='__main__':
    main()

  github路径:

https://github.com/DyLanCao/python_cabin.git

三 总结

 能让计算机做的,尽量使用计算机。

作者:虚生
出处:https://www.cnblogs.com/dylancao/
以声学降噪算法为核心的物联网音频解决方案提供商 ,提供基于声学技术为基础的智能硬件产品设计,开发和技术服务。
商务合作和技术探讨:邮箱:1173496664@qq.com weixin:18019245820 市场技术对接群:347609188
原文地址:https://www.cnblogs.com/dylancao/p/14663238.html