Last active
November 20, 2022 18:09
-
-
Save hanleybrand/5224673 to your computer and use it in GitHub Desktop.
python function that produces the same result as java's String.hashCode() found at http://garage.pimentech.net/libcommonPython_src_python_libcommon_javastringhashcode/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def java_string_hashcode(s): | |
h = 0 | |
for c in s: | |
h = (31 * h + ord(c)) & 0xFFFFFFFF | |
return ((h + 0x80000000) & 0xFFFFFFFF) - 0x80000000 |
Does it also work for python 3 integers? Which aren't same integers as in Java, more like BigInt ones
A quick test suggests it works, but I wonder if I miss some corner cases where it may fail
Ok, I think I have figured it out: & 0xFFFFFFFF
makes sure it stays a 4-byte int. Thanks for the snippet!
Does someone have a similar function in python for Java's Objects.hash(val1, val2...valn)
Works! 👍
Thanks!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks!