#include <stdio.h>
#include <string.h>
/*
djb2 hash function
Converts a string into an unsigned long value.
Note:
Different strings can sometimes produce
the same hash value (collision).
*/
unsigned long hash(const char *str)
{
unsigned long hash = 5381;
int c;
while ((c = *str++)) {
hash = ((hash << 5) + hash) + c; /* hash * 33 + c */
}
return hash;
}
int main(void)
{
const char *str1 = "Hello";
const char *str2 = "World";
unsigned long hash1 = hash(str1);
unsigned long hash2 = hash(str2);
printf("String 1: %s\n", str1);
printf("Hash 1 : %lu\n\n", hash1);
printf("String 2: %s\n", str2);
printf("Hash 2 : %lu\n\n", hash2);
/*
First compare hashes.
Hash comparison is very fast because
it compares two numbers.
*/
if (hash1 == hash2)
{
printf("Hashes match.\n");
/*
IMPORTANT:
A matching hash does NOT guarantee
the strings are equal.
We must compare the actual strings
to detect collisions.
*/
if (strcmp(str1, str2) == 0) {
printf("Strings are identical.\n");
}
else {
printf("Hash collision detected!\n");
}
}
else
{
printf("Hashes are different.\n");
printf("Strings are different.\n");
}
return 0;
}
/*
run:
String 1: Hello
Hash 1 : 210676686969
String 2: World
Hash 2 : 210694841677
Hashes are different.
Strings are different.
*/