Skip to content

Instantly share code, notes, and snippets.

@mengzhuo
Created March 9, 2015 07:40
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save mengzhuo/180cd6be8ba9e2743753 to your computer and use it in GitHub Desktop.
Save mengzhuo/180cd6be8ba9e2743753 to your computer and use it in GitHub Desktop.
DJB2 Hash in Python
#!/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'
@amakukha
Copy link

amakukha commented Nov 5, 2021

This is very slow and inefficient for long strings. You need to do & 0xFFFFFFFF on every step.

@nmmmnu
Copy link

nmmmnu commented Sep 7, 2022

why & on every lap?

speaking of which, why there is & 0xFF'FF'FF'FF anyway? to make it uint32_t ?

@amakukha
Copy link

amakukha commented Sep 7, 2022

@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

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