I'm working on CS50's pset 5, speller. I need a hash function for a hash table that will efficiently store all of the words on the dictionary (~140,000). I found this one online, but I don't understand how it works. I don't know what <<
or ^
mean. Here is the hash function, thank you! (I would really appreciate it if you could help me :))
int hash_it(char* needs_hashing)
{
unsigned int hash = 0;
for (int i=0, n=strlen(needs_hashing); i<n; i++)
hash = (hash << 2) ^ needs_hashing[i];
return hash % HASHTABLE_SIZE;
}
Those two are Bit-wise operators. These are easy to learn and must to learn for a programmer.
<<
- is a binary left shift operator.
Suppose variable "hash" binary is "0011".
hash << 2
becomes "1100".
And ^
is XOR operator. (If set in only one operand ...not in both)
Suppose in your code
hash << 2
gives "1100"
needs_hashing[1]
gives "1111"
then
(hash << 2) ^ needs_hashing[i]
gives "0011"
For a quick understanding bitwise operators, quickly walk here https://www.tutorialspoint.com/cprogramming/c_bitwise_operators.htm