• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

python语句计算文件的md5值以和字符串的hashcode值

武飞扬头像
李胖圆
帮助1

python语句计算md5值

md5值就是使用MD5 的数据摘要算法计算出来的一串数值。


用例:

  • 新建某一文件(作为测试),拿到文件的路径
import hashlib
import os
file_path = 'D:/*/*/*/pangyuan.txt'
def get_md5_01(file_path):
  if os.path.isfile(file_path):
    f = open(file_path, 'rb')
    f.seek(0, os.SEEK_END)
    fileLen=f.tell()
    f.seek(0, 0)
    body = f.read(fileLen)
    # print(str(body))
    # 拿到二进制数据
    md5_obj = hashlib.md5(body)
    # 二进制转为十六进制
    hash_code = md5_obj.hexdigest()
    f.close()
    # hash_code.lower() 字符串转小写
    # hash_code.upper() 字符串转大写
  return hash_code.upper()
  print(get_md5_01(file_path))
学新通

运行结果:

  • 大写:
    学新通
  • 小写:
    学新通

python计算hashcode值

  • python中的hash() 用于获取取一个对象(字符串或者数值等)的哈希值

用例:

import *
def convert_n_bytes(n, b):
  bits = b * 8
  return (n   2 ** (bits - 1)) % 2 ** bits - 2 ** (bits - 1)

def convert_4_bytes(n):
  return convert_n_bytes(n, 4)

def getHashCode(str):
  h = 0
  n = len(str)
  for i, c in enumerate(str):
    h = h   ord(c) * 31 ** (n - 1 - i)
  return convert_4_bytes(h)
# 直接拿上面的md5字符串进行验证
print(getHashCode(md5_01))
学新通

*注意字符串的大小写计算出的hashcode值不相同

结果:

  • 大写:
    学新通
  • 小写
    学新通

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhgfikah
系列文章
更多 icon
同类精品
更多 icon
继续加载