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.)
Python Code: n = float(input('Input a number: ')) print('Number is Positive. ' if n > 0 else 'It is Zero!' if n == 0 else 'Number is Negative. ')
Python hash() method Python hash() function is a built-in function and returns the hash value of an object if it has one. The hash value is an integer which is used to quickly compare dictionary keys while looking at a dictionary.
Example 1 – How hash() works in Python? Note – Hash values can range from positive integers to negative integers as well.
It's unfortunate that Python does not make a combine_hashes function available. It's not implemented in things like dict or list, the justification being that changing the hash of an object that already belongs to, e.g., a set wreaks havoc on the set's internal data structures.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With