python正整数函数,Python hash()函数的正整数

博客围绕Python中使用hash()函数获取对象的整数哈希值展开,因内置hash()可能返回负值,而需求是仅获取正值,且要在32位和64位平台合理工作。给出了将哈希值转换为对应平台正整数范围的解决方案,如使用sys和ctypes.c_size_t。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.)

解决方案>>> 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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值