如何手动计算字符串的哈希码? [英] How to calculate the hash code of a string by hand?
问题描述
我想知道如何手动计算给定字符串的哈希码.我了解在Java中,您可以执行以下操作:
I was wondering how to calculate the hash code for a given string by hand. I understand that in Java, you can do something like:
String me = "What you say what you say what?";
long whatever = me.hashCode();
这一切都很好,但我想知道如何手工完成.我知道给定的用于计算字符串的哈希码的公式类似于:
That's all good and dandy, but I was wondering how to do it by hand. I know the given formula for calculating the hash code of a string is something like:
S0 X 31 ^ (n-1) + S1 X 31 ^ (n-2) + .... + S(n-2) X 31 + S(n-1)
其中S表示字符串中的字符,n是字符串的长度.然后使用16位unicode,来自字符串me的第一个字符将计算为:
Where S indicates the character in the string, and n is the length of the string. Using 16 bit unicode then, the first character from string me would be computed as:
87 X (31 ^ 34)
但是,这会产生惊人的数字.我无法想象像这样将所有字符加在一起.那么,为了计算最低阶的32位结果,我该怎么办?上方的任何东西等于-957986661,我不是怎么计算呢?
However, that creates an insanely large number. I can't imagine adding all the characters together like that. So, in order to calculate the lowest-order 32 bits result then, what would I do? Long whatever from above equals -957986661 and I'm not how to calculate that?
推荐答案
看看java.lang.String
的源代码.
/**
* Returns a hash code for this string. The hash code for a
* <code>String</code> object is computed as
* <blockquote><pre>
* s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
* </pre></blockquote>
* using <code>int</code> arithmetic, where <code>s[i]</code> is the
* <i>i</i>th character of the string, <code>n</code> is the length of
* the string, and <code>^</code> indicates exponentiation.
* (The hash value of the empty string is zero.)
*
* @return a hash code value for this object.
*/
public int hashCode() {
int h = hash;
int len = count;
if (h == 0 && len > 0) {
int off = offset;
char val[] = value;
for (int i = 0; i < len; i++) {
h = 31*h + val[off++];
}
hash = h;
}
return h;
}
这篇关于如何手动计算字符串的哈希码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!