0

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...

7
  • Did you try this? This is valid (with warning) as C, but invalid as C++ because return type is missing.
    – MikeCAT
    Nov 5, 2020 at 14:52
  • @MikeCAT oh, I am really sorry I just missed the return type earlier. But I just fixed it.
    – SAM4RTH
    Nov 5, 2020 at 15:06
  • What exactly do you need explained? Nov 5, 2020 at 15:11
  • @500-InternalServerError I just want to implement this in my c program. So I need this code in C to I can use it. And I have no idea what this code is doing, what do these mean... c = *str++ and what is hash << 5, specifically what does << mean?
    – SAM4RTH
    Nov 5, 2020 at 15:15
  • << means shift left (in this context). hash << 5 is the same as hash * 32 only more efficient. Most compilers will do that optimization automatically but not necessarily for hash * 33 as is called for here. Nov 5, 2020 at 15:19

1 Answer 1

0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.