Search code examples
cdictionaryhashhashtable

How to write djb2 hashing function in C?


I am not able to figure out how to write the djb3 hashing function on C.

I searched the internet but I found it may be in C++...

unsigned long hash(unsigned char *str){
        unsigned long hash = 5381;
        int c;

        while (c = *str++)
            hash = ((hash << 5) + hash) + c; /* hash * 33 + c */

        return hash;
    }

and if you can explain this to me I will be really thankful...


Solution

  • Here is the code for djb2 Hashing function in C programming language!

    unsigned int hash(const char *word)
    {
        unsigned int hash = 5381;
        int c;
    
        while ((c = *word++))        // *str++ is going to the next address in memory, where the next char in the string is stored
        {
            if (isupper(c))
            {
                c = c + 32;
            }
    
            hash = ((hash << 5) + hash) + c; // hash * 33 + c   // hash << 5 = hash * 2^5
        }
    
        return hash % N;
    }
    

    Thanks to @500-InternalServerError for solving my doubts.