Skip to content

Instantly share code, notes, and snippets.

@papamuziko
Created May 4, 2020 17:54
Show Gist options
  • Save papamuziko/7bb52dfbb859fdffc4bd0f95b76f71e8 to your computer and use it in GitHub Desktop.
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.
/**
* 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);
}
@dbaba2011
Copy link

It works as expected

@The-Leo
Copy link

The-Leo commented Jul 7, 2023

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!

@TheKingsident
Copy link

Very simple, yet has good distribution properties

@mokhtarmramadan
Copy link

It works, Thanks

@MinightDev
Copy link

ty

@MATRIX30
Copy link

MATRIX30 commented Oct 6, 2023

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

@Echewis
Copy link

Echewis commented Nov 2, 2023

The code works fine

@Brendon45
Copy link

interesting code indeed, it works fine. thanks

@iygeal
Copy link

iygeal commented Dec 22, 2023

Most interesting is the efficient use of bitwise left shift

@Akpevwe11
Copy link

interesting to know about the djb2 algorithm.

@MYacinedouaouria
Copy link

It works as expected

@emma-obelenge
Copy link

the djb2 algorithm is sleek

@yam1er
Copy link

yam1er commented Feb 18, 2024

Thank all good here

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