Python hash()函数的正整数 [英] Positive integer from Python hash() function
问题描述
我想使用Python hash()
函数从对象中获取整数哈希值。但是,内置的 hash()
可以给出负值,我只想要积极的。我希望它能够在32位和64位平台上理性工作。
即,在32位Python中, hash()
可以返回范围 -2 ** 31
到<$的整数c $ c> 2 ** 31 - 1 。
在64位系统上, hash()
可以返回 -2 ** 63
到 2 ** 63 - 1
。
但是我想在 0
到32位系统上的 2 ** 32-1
, 0
在64位系统上转换为 2 ** 64-1
。
转换散列的最佳方法是什么在32位或64位目标平台的范围内,它的值是否等价于正值?
(上下文:我试图创建一个新的 random.Random
style class。根据 random.Random.seed()
docs ,种子可选参数x可以是任何可哈希对象。所以我想复制该功能,除了我的种子算法)
使用 sys.maxsize
:
>> ;> import sys
>>> sys.maxsize
9223372036854775807L
>>> hash('asdf')
-618826466
>>> hash('asdf')%((sys.maxsize + 1)* 2)
18446744073090725150L
使用 ctypes.c_size_t
:
>>> import ctypes
>>> ctypes.c_size_t(hash('asdf'))。value
18446744073090725150L
I want to use the Python hash()
function to get integer hashes from objects. But built-in hash()
can give negative values, and I want only positive. And I want it to work sensibly on both 32-bit and 64-bit platforms.
I.e. on 32-bit Python, hash()
can return an integer in the range -2**31
to 2**31 - 1
.
On 64-bit systems, hash()
can return an integer in the range -2**63
to 2**63 - 1
.
But I want a hash in the range 0
to 2**32-1
on 32-bit systems, and 0
to 2**64-1
on 64-bit systems.
What is the best way to convert the hash value to its equivalent positive value within the range of the 32- or 64-bit target platform?
(Context: I'm trying to make a new random.Random
style class. According to the random.Random.seed()
docs, the seed "optional argument x can be any hashable object." So I'd like to duplicate that functionality, except that my seed algorithm can't handle negative integer values, only positive.)
Using sys.maxsize
:
>>> import sys
>>> sys.maxsize
9223372036854775807L
>>> hash('asdf')
-618826466
>>> hash('asdf') % ((sys.maxsize + 1) * 2)
18446744073090725150L
Alternative using ctypes.c_size_t
:
>>> import ctypes
>>> ctypes.c_size_t(hash('asdf')).value
18446744073090725150L
这篇关于Python hash()函数的正整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!