读书人

DJBX33A哈希函数兑现Bash

发布时间: 2012-08-30 09:55:54 作者: rapoo

DJBX33A哈希函数实现——Bash

?

DJBX33A 哈希函数又叫做time33 哈希函数,PHP、Perl、Apache中都是用该方法做为其哈希函数的实现。

?

本文就对该哈希函数做一简单的介绍,并用Bash对其进行实现。

?

该方法十分简单,将字符串中的每个字符的ascii码迭代*33加在一起即可。即hash(i)=hash(i-1)*33+ascii(i)。

?

假如字符串为:abc,则结果就是hashCode=(ascii(a)*33+ascii(b))*33+ascii(c)

?

PHP中的实现见博客:PHP中的hash函数实现

?

本文使用Bash实现该hash函数,代码如下:

?

#!/home/admin/bin/bash_bin/bash_4declare -A HashAsciiTable;for c in {a..z} {A..Z}do    HashAsciiTable[$c]=`printf "%d" "'$c"`;donefunction hash {    inputStr=$1    strLength=${#inputStr};    hashValue=5381;    for((i=0;i<strLength;i++))    do        char=${inputStr:$i:1};        code=0;        if [ -n ${HashAsciiTable[$char]} ]; then            code=${HashAsciiTable[$char]};        fi        hashValue=$((code+hashValue*33));    done    eval $2=$hashValue;}## call the hash functionhash "abcdefasdff2123as" hashCode;## echo the hash code for input stringecho $hashCode

?

结果为:1294730825853141650

?

1 楼 liuzhiqiangruc 2012-06-14 其实这个更多的是练习bash_4中的关联数组。

读书人网 >编程

热点推荐