Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hash Code what Is this?

int value = 5381;

for (int i = 0; i < item.length(); i++) {
  value = value * 33 + item.charAt(i);
}

value &= 0x7fffffff;
value %= size;

This is Bernstein's hash code. I get everything except for the last two lines. What do they do? They also produce an error in the Java compiler, so they are clearly not valid code. How else could they be represented?

I almost don't care what they do, as long as they work lol :P

like image 453
user Avatar asked Mar 09 '26 14:03

user


1 Answers

The purpose of the bitwise and & is to shift all values into a positive integer range. This probably preserves the even distribution created by the former operations better than a simple absolute value operation. Also, the general reason for getting rid of the negative sign, as @yshavit points out in the comments, is that the value will probably eventually be used as an index of some sort.

The purpose of the modulo % is to make the hash code fit in a limited sized space.

like image 51
The111 Avatar answered Mar 11 '26 05:03

The111