data-structures · intermediate · ~15 min

djb2 string hash

Turn a string into a reproducible hash value.

Challenge

Compute the classic djb2 hash of a string.

Task

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.

Input

s: a NUL-terminated string (may be empty). Treat each byte as unsigned char.

Output

unsigned long: the djb2 hash value.

Example

""     ->   5381
"a"    ->   177670
"ab"   ->   5863208

Edge cases

  • The empty string hashes to the seed value 5381.

Rules

  • Use the exact recurrence hash = hash * 33 + (unsigned char)c, starting from 5381.

Input format

s: a NUL-terminated string (may be empty).

Output format

unsigned long: the djb2 hash.

Constraints

Seed 5381; per byte hash = hash*33 + (unsigned char)c.

Starter code

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.