data-structures · intermediate · ~15 min
Turn a string into a reproducible hash value.
Compute the classic djb2 hash of a string.
Implement unsigned long djb2(const char *s). Start the hash at 5381 and, for each byte of the string, update it with hash = hash * 33 + byte.
s: a NUL-terminated string (may be empty). Treat each byte as unsigned char.
unsigned long: the djb2 hash value.
"" -> 5381
"a" -> 177670
"ab" -> 5863208
hash = hash * 33 + (unsigned char)c, starting from 5381.s: a NUL-terminated string (may be empty).
unsigned long: the djb2 hash.
Seed 5381; per byte hash = hash*33 + (unsigned char)c.
unsigned long djb2(const char *s) {
/* TODO */
return 5381;
}
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.