Created
March 9, 2015 07:40
-
-
Save mengzhuo/180cd6be8ba9e2743753 to your computer and use it in GitHub Desktop.
DJB2 Hash in Python
This file contains hidden or 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
#!/usr/bin/env python | |
# encoding: utf-8 | |
def hash_djb2(s): | |
hash = 5381 | |
for x in s: | |
hash = (( hash << 5) + hash) + ord(x) | |
return hash & 0xFFFFFFFF | |
hex(hash_djb2(u'hello world, 世界')) # '0xa6bd702fL' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@nmmmnu , yes. Because Python has bignum arithmetic by default. If you don't truncate the integer to uint32 on every step, the
hash
value will grow indefinitely and take longer and longer CPU time to process.On top of that, DJB2 is not a good hash. FNV-1a is way better while being simple and similar in performance. See: https://gist.github.com/amakukha/7854a3e910cb5866b53bf4b2af1af968