Search code examples
c++hashhash-function

djb2 by Dan Bernstein for c++


I've tried to translate djb2 hash function from c-code

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;
}

to c++ code, but i have segmentation fault.

int hf(std::string s){
    unsigned long hash = 5381;
    char c;
    for(int i=0; i<s.size(); i++){
        c=s[i++];
        hash = ((hash << 5) + hash) + c; /* hash * 33 + c */
    }
    return hash;

Where is my mistake? Thanks in advance


Solution

  • You want s[i], not s[i++]. Even better would be to use range-based for.

    int hf(std::string const& s) {
        unsigned long hash = 5381;
        for (auto c : s) {
            hash = (hash << 5) + hash + c; /* hash * 33 + c */
        }
        return hash;
    }