Tenescu Andrei Tenescu Andrei - 5 months ago 82
Javascript Question

Javascript hashing algorithm

I'm trying to learn how to do some basic hashing in Javascript and I've come across the following algorithm:

var hash = 0;
for (i = 0; i < this.length; i++) {
char = str.charCodeAt(i);
hash = ((hash<<5)-hash)+char;
hash = hash & hash;

I don't really understand how it works and I was hoping you could help me out. In particular I don't understand
hash = hash & hash
. Thank you for your replies.

Note: For anyone looking for the source, it's an implementation of Java’s String.hashCode():

Answer Source

The step

  hash = ((hash << 5) - hash) + char;

is effectively:

  hash = ((hash * 32) - hash) + char;


  hash = hash & hash;

will only change the value if the number has overflowed the integer range (32 bits, or maybe 31). (I wouldn't do it that way but it's a matter of style.)

In that code, the variables "i" and "char" should be declared:

var hash = 0, i, char;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download