代码之家  ›  专栏  ›  技术社区  ›  Bob Fang

如何将字符串散列为8位数字?

  •  176
  • Bob Fang  · 技术社区  · 12 年前

    有没有什么可以让我把一个随机字符串散列成一个8位数的数字,而不需要自己实现任何算法?

    4 回复  |  直到 7 年前
        1
  •  245
  •   Boris Verkhovskiy Brian Clapper    5 年前

    是的,您可以使用内置 hashlib 模块或内置 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
    
        2
  •  160
  •   JJC    9 年前

    Raymond的答案对蟒蛇2来说很好(不过,你不需要abs(),也不需要10**8左右的parens)。然而,对于蟒蛇3,有一些重要的注意事项。首先,您需要确保您正在传递一个编码的字符串。如今,在大多数情况下,最好避开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 -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的方法。

        3
  •  11
  •   user8948052    8 年前

    为了完成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
    
        4
  •  5
  •   Cara Duf    3 年前

    从Python 3.10开始,将字符串散列为8个十六进制数字摘要的另一种快速方法是使用 shake.hexdigest(4) :

    import hashlib
    h=hashlib.shake_128(b"my ascii string").hexdigest(4)
    #34c0150b
    

    注意4而不是8,因为摘要的长度是作为参数给定的数字的两倍。

    当然要注意散列冲突。

    推荐文章