Skip to content

Instantly share code, notes, and snippets.

@hanleybrand
Last active November 20, 2022 18:09
Show Gist options
  • Star 15 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save hanleybrand/5224673 to your computer and use it in GitHub Desktop.
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/
def java_string_hashcode(s):
h = 0
for c in s:
h = (31 * h + ord(c)) & 0xFFFFFFFF
return ((h + 0x80000000) & 0xFFFFFFFF) - 0x80000000
@noomz
Copy link

noomz commented Jun 29, 2017

Thanks!

@alexeygrigorev
Copy link

alexeygrigorev commented Dec 28, 2017

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

@alexeygrigorev
Copy link

Ok, I think I have figured it out: & 0xFFFFFFFF makes sure it stays a 4-byte int. Thanks for the snippet!

@syerrawa
Copy link

Does someone have a similar function in python for Java's Objects.hash(val1, val2...valn)

@shauway
Copy link

shauway commented Aug 12, 2021

Works! 👍

@talbz
Copy link

talbz commented Nov 20, 2022

Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment