Skip to content

Instantly share code, notes, and snippets.

@hanleybrand
Last active November 20, 2022 18:09
Show Gist options
  • Select an option

  • Save hanleybrand/5224673 to your computer and use it in GitHub Desktop.

Select an option

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

noomz commented Jun 29, 2017

Copy link
Copy Markdown

Thanks!

@alexeygrigorev

alexeygrigorev commented Dec 28, 2017

Copy link
Copy Markdown

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
Copy Markdown

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

@syerrawa

Copy link
Copy Markdown

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

@shauway

shauway commented Aug 12, 2021

Copy link
Copy Markdown

Works! 👍

@talbz

talbz commented Nov 20, 2022

Copy link
Copy Markdown

Thanks!

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