如何将字符串哈希为8位数?

时间:2013-04-15 06:10:19

标签: python arrays algorithm random hash

无论如何,我可以将随机字符串散列为8位数而不自行实现任何算法吗?

4 个答案:

答案 0 :(得分:98)

是的,您可以使用内置的hashlib模块或内置的hash功能。然后,在整数形式的散列上使用模运算或字符串切片操作来切断最后八位数字:

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

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

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

答案 1 :(得分:50)

Raymond的答案对于python2来说很棒(但是,你不需要abs(),也不需要10 ** 8左右的parens)。但是,对于python3,有一些重要的警告。首先,您需要确保传递编码的字符串。这些天来,在大多数情况下,回避sha-1并使用像sha-256这样的东西也可能更好。因此,hashlib方法将是:

>>> import hashlib
>>> s = 'your string'
>>> int(hashlib.sha256(s.encode('utf-8')).hexdigest(), 16) % 10**8
80262417

如果你想使用hash()函数,重要的警告是,与Python 2.x不同,在Python 3.x中,hash()的结果只能在一个进程中保持一致,而不是在python调用。见这里:

$ python -V
Python 2.7.5
$ python -c 'print(hash("foo"))'
-4177197833195190597
$ python -c 'print(hash("foo"))'
-4177197833195190597

$ python3 -V
Python 3.4.2
$ python3 -c 'print(hash("foo"))'
5790391865899772265
$ python3 -c 'print(hash("foo"))'
-8152690834165248934

这意味着建议使用基于hash()的解决方案,可以简化为:

hash(s) % 10**8

只会在给定的脚本运行中返回相同的值:

#Python 2:
$ python2 -c 's="your string"; print(hash(s) % 10**8)'
52304543
$ python2 -c 's="your string"; print(hash(s) % 10**8)'
52304543

#Python 3:
$ python3 -c 's="your string"; print(hash(s) % 10**8)'
12954124
$ python3 -c 's="your string"; print(hash(s) % 10**8)'
32065451

所以,根据你的应用程序中是否重要(它确实在我的应用程序中),你可能会想要坚持基于hashlib的方法。

答案 2 :(得分:2)

只是为了完成JJC的回答,在python 3.5.3中,如果你以这种方式使用hashlib,行为是正确的:

$ python3 -c '
import hashlib
hash_object = hashlib.sha256(b"Caroline")
hex_dig = hash_object.hexdigest()
print(hex_dig)
'
739061d73d65dcdeb755aa28da4fea16a02b9c99b4c2735f2ebfa016f3e7fded
$ python3 -c '
import hashlib
hash_object = hashlib.sha256(b"Caroline")
hex_dig = hash_object.hexdigest()
print(hex_dig)
'
739061d73d65dcdeb755aa28da4fea16a02b9c99b4c2735f2ebfa016f3e7fded

$ python3 -V
Python 3.5.3

答案 3 :(得分:-2)

我正在分享由@Raymond Hettinger实施的解决方案的nodejs实施。

var crypto = require('crypto');
var s = 'she sells sea shells by the sea shore';
console.log(BigInt('0x' + crypto.createHash('sha1').update(s).digest('hex'))%(10n ** 8n));