各种编程语言版本的BKDRHash实现

//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;
}
//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;
}
//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;
}
//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
//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; 
}
原字符串:jdfgsdhfsdfsd 6445dsfsd7fg/*/+bfjsdgf%$^
运算结果:3255416723

发表评论

电子邮件地址不会被公开。 必填项已用*标注