Created
October 5, 2017 22:06
-
-
Save MohamedTaha98/ccdf734f13299efb73ff0b12f7ce429f to your computer and use it in GitHub Desktop.
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
// 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; | |
} |
Thanks for the code! helped me build a hash table for CS50 course.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi,
In C when you do an assignment like
x = 2
, it's considered a function, soif(x = 2)
would be evaluated astrue
.Now if we break down the statement in the while we:
*str
), in other words, we get the character at this address in the string.c
.str++
).As said earlier, the character assigned to
c
gets evaluated as a boolean, the last character of a C string'\0'
is evaluated tofalse
so the while loop exits when reaching the end of the string.Hope that helped!