常用的散列函数有哪些

JavaScript07

常用的散列函数有哪些,第1张

常用的哈希函数

通用的哈希函数库有下面这些混合了加法和一位操作的字符串哈希算法。下面的这些算法在用法和功能方面各有不同,但是都可以作为学习哈希算法的实现的例子。(其他版本代码实现见下载)

1.RS

从Robert Sedgwicks的 Algorithms in C一书中得到了。我(原文作者)已经添加了一些简单的优化的算法,以加快其散列过程。

[java] view plaincopyprint?

public long RSHash(String str)

{

int b     = 378551

int a     = 63689

long hash = 0

for(int i = 0 i < str.length() i++)

{

hash = hash * a + str.charAt(i)

a    = a * b

}

return hash

}

2.JS

Justin Sobel写的一个位操作的哈希函数。

[c-sharp] view plaincopyprint?

public long JSHash(String str)

{

long hash = 1315423911

for(int i = 0 i < str.length() i++)

{

hash ^= ((hash << 5) + str.charAt(i) + (hash >> 2))

}

return hash

}

3.PJW

该散列算法是基于贝尔实验室的彼得J温伯格的的研究。在Compilers一书中(原则,技术和工具),建议采用这个算法的散列函数的哈希方法。

[java] view plaincopyprint?

public long PJWHash(String str)

{

long BitsInUnsignedInt = (long)(4 * 8)

long ThreeQuarters     = (long)((BitsInUnsignedInt  * 3) / 4)

long OneEighth         = (long)(BitsInUnsignedInt / 8)

long HighBits          = (long)(0xFFFFFFFF) << (BitsInUnsignedInt - OneEighth)

long hash              = 0

long test              = 0

for(int i = 0 i < str.length() i++)

{

hash = (hash << OneEighth) + str.charAt(i)

if((test = hash & HighBits)  !=

可以用for循环配合charAt函数遍历字符串。

1、定义一个字符串并将字符串赋值给一个变量,这里以变量名为str为例:

2、新建一个for循环,循环从0开始,循环次数为“str.length”,它的意思是循环次数为字符串的长度:

3、在for循环中添加“str.charAt(i)”,charAt中的值为循环中的次数,然后将结果输出,这样字符串就被遍历出来了:

需要准备的材料分别是:电脑、html编辑器、浏览器。

1、首先,打开html编辑器,新建html文件,例如:index.html。

2、在index.html的<script>标签中,再输入js代码:var a = 'ABC123456'var b = a.substr(3)document.body.innerText = b。

3、浏览器运行index.html页面,此时会发现后面的数字内容被用js取出来了。