Junior — Middle
Can you provide an example of a hashing algorithm for string data?
sobes.tech AI
Answer from AI
One of the simple and popular string hashing algorithms in C/C++ is the djb2 algorithm, proposed by Daniel Bernstein. It is well-suited for strings and easy to implement:
unsigned long djb2_hash(const char *str) {
unsigned long hash = 5381;
int c;
while ((c = *str++)) {
hash = ((hash << 5) + hash) + c; // hash * 33 + c
}
return hash;
}
This algorithm processes each character of the string sequentially, multiplying the current hash by 33 and adding the character code. It is often used because of its good hash distribution and simplicity.