- 論壇徽章:
- 0
|
5可用積分
用nawk (僅限于shell,請不要有用python,perl實(shí)現(xiàn)的回答),實(shí)現(xiàn)ACE中的一個(gè)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;
- }
復(fù)制代碼 以上我用shell已經(jīng)實(shí)現(xiàn),但效率實(shí)在太低,可能我水平有限,寫不出高效率的腳本,請達(dá)人賜教。
另外,我用gawk實(shí)現(xiàn)了這個(gè)腳本,效率大大提升,但移植到Solaris下,原生的awk和nawk不支持gawk的位運(yùn)算操作,請教達(dá)人如何用nawk實(shí)現(xiàn)呢?
shell的實(shí)現(xiàn):- #!/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"
復(fù)制代碼 gawk的實(shí)現(xiàn):
- #!/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
復(fù)制代碼 |
|