-
-
Save papamuziko/7bb52dfbb859fdffc4bd0f95b76f71e8 to your computer and use it in GitHub Desktop.
djb2: This algorithm (k=33) was first reported by dan bernstein many years ago in comp.lang.c. another version of this algorithm (now favored by bernstein) uses xor: hash(i) = hash(i - 1) * 33 ^ str[i]; the magic of number 33 (why it works better than many other constants, prime or not) has never been adequately explained.
This file contains 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
/** | |
* hash_djb2 - implementation of the djb2 algorithm | |
* @str: string used to generate hash value | |
* | |
* Return: hash value | |
*/ | |
unsigned long int hash_djb2(const unsigned char *str) | |
{ | |
unsigned long int hash; | |
int c; | |
hash = 5381; | |
while ((c = *str++)) | |
{ | |
hash = ((hash << 5) + hash) + c; /* hash * 33 + c */ | |
} | |
return (hash); | |
} |
Very simple, yet has good distribution properties
It works, Thanks
ty
what an Amazing way to code. just learn a new trick on how to iterate over a character array.
Just coming from TDD in python I think Sir @papamuziko can we add a check to handle when the str is NULL cause I tried and the function gives a segmentation fault
The code works fine
interesting code indeed, it works fine. thanks
Most interesting is the efficient use of bitwise left shift
interesting to know about the djb2 algorithm.
It works as expected
the djb2 algorithm is sleek
Thank all good here
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
So basically, this function is used to generate hash values for strings.
It takes a string as input, represented by the parameter str. The string is expected to be an array of unsigned characters. The function initializes a variable hash to the initial value of 5381. This value is an arbitrary starting point for the hash calculation. The function iterates through each character of the input string using a while loop and assigns it to the variable c. Amazing!