# 各种编程语言版本的BKDRHash实现
2017-08-24
# C++
unsigned int BKDRHash(string str) {
unsigned int seed = 131;
unsigned int hash = 0;
unsigned int i = 0;
unsigned int len = str.length();
for (i = 0; i < len; i++)
{
hash = (hash * seed) + (str[i]);
}
return hash;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
# C
unsigned int BKDRHash(char* str, unsigned int length) {
unsigned int seed = 131;
unsigned int hash = 0;
unsigned int i = 0;
for (i = 0; i < length; str++, i++)
{
hash = (hash * seed) + (*str);
}
return hash;
}
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
# C#
public static uint BKDRHash(string str)
{
uint seed = 131;
uint hash = 0;
uint i = 0;
for (i = 0; i < str.Length; i++)
{
hash = (hash * seed) + ((byte)str[(int)i]);
}
return hash;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
# VB
Public Shared Function BKDRHash(str As String) As UInteger
Dim seed As UInteger = 131
Dim hash As ULong = 0
Dim i As UInteger = 0
For i = 0 To str.Length - 1
hash = ((hash * seed) + CByte(AscW(str(CInt(i)))) And UInteger.MaxValue)
Next
Return hash
End Function
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
# java
public static long BKDRHash(byte[] b){
int seed = 131;
long hash = 0;
for (int i = 0; i < b.length; i++){
hash = ( ((hash*seed) & 0x0FFFFFFFFL) + ((int) b[i] & 0x0FF) ) & 0x0FFFFFFFFL;
}
return hash;
}
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
# 结果
原字符串:jdfgsdhfsdfsd 6445dsfsd7fg/*/+bfjsdgf%$^ 运算结果:3255416723