Skip to content

Commit 62f7561

Browse files
bnMikheilicclauss
andauthored
Hash djb2 (#2098)
* implement hash * fix flake8 error * Update hashes/djb2.py * Update hashes/djb2.py * Long lines * def djb2(s: str) -> int: Co-authored-by: Christian Clauss <[email protected]>
1 parent 924ef9b commit 62f7561

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

hashes/djb2.py

+35
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
"""
2+
This algorithm (k=33) was first reported by Dan Bernstein many years ago in comp.lang.c
3+
Another version of this algorithm (now favored by Bernstein) uses xor:
4+
hash(i) = hash(i - 1) * 33 ^ str[i];
5+
6+
First Magic constant 33:
7+
It has never been adequately explained.
8+
It's magic because it works better than many other constants, prime or not.
9+
10+
Second Magic Constant 5381:
11+
12+
1. odd number
13+
2. prime number
14+
3. deficient number
15+
4. 001/010/100/000/101 b
16+
17+
source: http://www.cse.yorku.ca/~oz/hash.html
18+
"""
19+
20+
21+
def djb2(s: str) -> int:
22+
"""
23+
Implementation of djb2 hash algorithm that
24+
is popular because of it's magic constants.
25+
26+
>>> djb2('Algorithms')
27+
3782405311
28+
29+
>>> djb2('scramble bits')
30+
1609059040
31+
"""
32+
hash = 5381
33+
for x in s:
34+
hash = ((hash << 5) + hash) + ord(x)
35+
return hash & 0xFFFFFFFF

0 commit comments

Comments
 (0)