如何将字符串散列成 8 位数字? [英] How to hash a string into 8 digits?

查看:18
本文介绍了如何将字符串散列成 8 位数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

无论如何,我可以在不自己实现任何算法的情况下将一个随机字符串散列成一个 8 位数字吗?

解决方案

是的,你可以使用内置的 hashlib 模块或内置的 hash 函数.然后,对散列的整数形式使用模运算或字符串切片运算去除最后八位数字:

<预><代码>>>>s = '她在海边卖贝壳'>>># 使用哈希库>>>导入哈希库>>>int(hashlib.sha1(s.encode("utf-8")).hexdigest(), 16) % (10 ** 8)58097614L>>># 使用哈希()>>>abs(hash(s)) % (10 ** 8)82148974

Is there anyway that I can hash a random string into a 8 digit number without implementing any algorithms myself?

解决方案

Yes, you can use the built-in hashlib module or the built-in hash function. Then, chop-off the last eight digits using modulo operations or string slicing operations on the integer form of the hash:

>>> s = 'she sells sea shells by the sea shore'

>>> # Use hashlib
>>> import hashlib
>>> int(hashlib.sha1(s.encode("utf-8")).hexdigest(), 16) % (10 ** 8)
58097614L

>>> # Use hash()
>>> abs(hash(s)) % (10 ** 8)
82148974

这篇关于如何将字符串散列成 8 位数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆