12,352,739 members (54,141 online)

Email

Password

Sign in using

Hello.

What does this code do?

And what is the purpose of the "for" while?

What does this code do?

And what is the purpose of the "for" while?

```
int hash(const char *str)
{
if (str != 0)
{
unsigned h = str [0];
for (int i = 1; str [i] != 0; ++i)
h = (h << 5) - h + str [i];
return h % HASH_SIZE; // remainder
}
else
{
return -1;
}
}
```

smss IR407

Comments

This seems to be the java string hashing algorithm[^]. It is a variant of the djb2[^] with different constants[^]. Here[^] you can find some explanation about the constants of djb2.

Comments

Thanks my friend, but the djb2 algorithm is different from this. I wanna to know the this hash algorithm.

The djb2 formula is : hash = ((hash << 5) + hash) + c; /* hash * 33 + c */

but in this algorithm the code is different : h = (h << 5) - h + str [i];

but in this algorithm the code is different : h = (h << 5) - h + str [i];

Yes. Because it uses 31 instead of 33 thats why I told you its java.

(h<<5)-h == h*31

I think the above equation clarifies some things, the original shifted version is "manual optimization" for older C compilers.

(h<<5)-h == h*31

I think the above equation clarifies some things, the original shifted version is "manual optimization" for older C compilers.

Thank you my friend, but I still do not know the mean of the "hash", I think "hash" point to the count of the arguments in a string, is this true?

Please read these:

http://en.wikipedia.org/wiki/Hash_function

http://en.wikipedia.org/wiki/Hash_table

If you still have concenrs than search for hash-related tutorials with google, sooner or later you will get it. If you don't succeed then go on learning easier material until you reach a level to understand hashing.

http://en.wikipedia.org/wiki/Hash_function

http://en.wikipedia.org/wiki/Hash_table

If you still have concenrs than search for hash-related tutorials with google, sooner or later you will get it. If you don't succeed then go on learning easier material until you reach a level to understand hashing.

Comments

I know "for" and "while", but I do not know the "hash" function target's ...

Hash function is http://en.wikipedia.org/wiki/Hash_function

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject,
503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada
+1 416-849-8900 x 100

Where from you picked the code that you have no idea on what is happening?

:D