- 论坛徽章:
- 0
|
5可用积分
用nawk (仅限于shell,请不要有用python,perl实现的回答),实现ACE中的一个hash算法,源代码如下:- u_long
- ACE::hash_pjw (const char *str, size_t len)
- {
- u_long hash = 0;
- for (size_t i = 0; i < len; i++)
- {
- const char temp = str[i];
- hash = (hash << 4) + (temp * 13);
- u_long g = hash & 0xf0000000;
- if (g)
- {
- hash ^= (g >> 24);
- hash ^= g;
- }
- }
- return hash;
- }
复制代码 以上我用shell已经实现,但效率实在太低,可能我水平有限,写不出高效率的脚本,请达人赐教。
另外,我用gawk实现了这个脚本,效率大大提升,但移植到Solaris下,原生的awk和nawk不支持gawk的位运算操作,请教达人如何用nawk实现呢?
shell的实现:- #!/bin/bash
- hash_pjw()
- {
- hash=0
- in="$1"
- for (( i = 0; i < ${#in}; ++i ))
- {
- temp=`printf "%d" "'${in:i:1}"`
- hash=$(( (hash<<4) + (temp*13) ))
- g=$(( hash & 0xf0000000 ))
- #echo temp[$temp]hash[$hash]g[$g]
-
- if [ -n "$g" ]; then
- hash=$(( hash ^= (g >> 24) ))
- hash=$(( hash ^= g ))
- fi
- }
- echo $hash
- }
- hash_pjw "$1"
复制代码 gawk的实现:
- #!/bin/bash
- hash_pjw()
- {
- echo "$1" | gawk 'BEGIN{}
- function ord(c)
- {
- for( i=0;i<256;i++ ) {
- ch = sprintf("%c",i);
- assii[ch] = i;
- }
- return assii[c]
- }
- {
- str=$0
- for(j=1;j<=length(str);j++){
- temp = ord( substr(str,j,1) )
- hash = ( lshift(hash,4) + temp*13 )
- g = and(hash,0xf0000000)
- #print temp,hash,g
- if(g){
- hash = xor(hash,rshift(g,24))
- hash = xor(hash,g)
- }
- }
- print hash
- }'
- }
- hash_pjw $1
复制代码 |
|