Skip to content

Instantly share code, notes, and snippets.

@MohamedTaha98
Created October 5, 2017 22:06
Show Gist options
  • Select an option

  • Save MohamedTaha98/ccdf734f13299efb73ff0b12f7ce429f to your computer and use it in GitHub Desktop.

Select an option

Save MohamedTaha98/ccdf734f13299efb73ff0b12f7ce429f to your computer and use it in GitHub Desktop.
// Djb2 hash function
unsigned long hash(char *str) {
unsigned long hash = 5381;
int c;
while ((c = *str++))
hash = ((hash << 5) + hash) + c; /* hash * 33 + c */
return hash % NUM_BUCKETS;
}
@gatsby003
Copy link
Copy Markdown

thank you ! This helped me with building a sweet hash table.

@MarcusXavierr
Copy link
Copy Markdown

Thanks man

@geekyDrake
Copy link
Copy Markdown

Thanks for the code - really helped!!

@hein-j
Copy link
Copy Markdown

hein-j commented Nov 2, 2020

thank you so much! the one that's widely circulating wouldn't compile. But this one did.

@XBoy-352
Copy link
Copy Markdown

its not compiling and its saying "conflicting types for 'hash'" and looks like the unsigned long hash(char *str) and then again unsigned long hash = 5381 are conflicting

@Ernestgio
Copy link
Copy Markdown

Thank you for the code! :D

@wbarbosa0
Copy link
Copy Markdown

wbarbosa0 commented Apr 22, 2021

its not compiling and its saying "conflicting types for 'hash'" and looks like the unsigned long hash(char *str) and then again unsigned long hash = 5381 are conflicting

Write like it this:

unsigned long hash = 5381L;

@BlachTheHole
Copy link
Copy Markdown

thanks very cool

@mongnak
Copy link
Copy Markdown

mongnak commented Sep 18, 2021

hi I'm noob
what does while ((c=*str++)) means?

@FtZPetruska
Copy link
Copy Markdown

hi I'm noob what does while ((c=*str++)) means?

Hi,

In C when you do an assignment like x = 2, it's considered a function, so if(x = 2) would be evaluated as true.

Now if we break down the statement in the while we:

  • de-reference str (*str), in other words, we get the character at this address in the string.
  • we assign the value to c.
  • we advance the str pointer to the next character (str++).
    As said earlier, the character assigned to c gets evaluated as a boolean, the last character of a C string '\0' is evaluated to false so the while loop exits when reaching the end of the string.

Hope that helped!

@PeterTreichel
Copy link
Copy Markdown

Thanks for the code! helped me build a hash table for CS50 course.

@ArthurTota
Copy link
Copy Markdown

Thanks a lot for this sharing

@M2G
Copy link
Copy Markdown

M2G commented May 13, 2026

thx for sharing

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