String hashing with DJB2
What you'll learn: How to turn a string of text into a unique numerical index using a fast and famously reliable algorithm.
The Magic of Fingerprinting
In a hash table, we need a way to turn a piece of data—like the username "Alice"—into an array index. Computers are great at math with numbers, but strings are just a messy sequence of characters. To bridge this gap, we use a hash function.
Think of a hash function like a fingerprint scanner. It takes a complex object (the string) and produces a consistent, simplified ID (the hash value). While there are many ways to do this, the DJB2 algorithm, created by Dan Bernstein, is a classic favorite because it is incredibly fast and does an excellent job of spreading different strings across the table to avoid "collisions."
How DJB2 Works
The logic is surprisingly simple. We start with a "magic" seed number, 5381, and then loop through every character in the string. For each character, we perform a bit of "bit-shifting" and addition.
unsigned long hash_djb2(unsigned char *str) {
unsigned long hash = 5381;
int c;
while ((c = *str++)) {
/* hash * 33 + c */
hash = ((hash << 5) + hash) + c;
}
return hash;
}
Why those numbers?
You might wonder why we use 5381 and 33. These are essentially "magic constants."
- 5381: This prime number was chosen because it results in fewer collisions for common English strings.
- The Shift (
<< 5): This is a programmer’s trick. Shifting a number left by 5 bits is the same as multiplying it by 32. By adding the originalhashto it ((hash << 5) + hash), we effectively multiply by 33.
Multiplying by 33 ensures that each character heavily influences the final result, "shuffling" the bits of our hash so that even similar words like "cat" and "car" result in wildly different numbers. Once you have this large number, you simply use the modulo operator (%) with your array size to find the exact bucket where your data belongs.
Key takeaway
DJB2 is a fast, reliable string hash that uses the number 33 and a prime seed to create unique "fingerprints" for text.