#includeunsignedintgetHashNum(constchar*str,unsignedintlen,unsignedintmaxPrime){registerunsignedintsum=0;registerunsignedinth=0;registerunsignedshort*p=(unsignedshort*)str;registerunsignedshort*s=(unsignedshort*)str;printf("str:%s,len:%d,h:%d,maxPrime:%d\n",p,len,h,maxPrime);while(p-s
2 回答
回首忆惘然
TA贡献1847条经验 获得超11个赞
对str的操作越界了,unsignedshortp,p++实际往后对(char*)str移动了sizeof(unsignedshort)=4的距离,如果str长度为3,第一次循环就会跑出str的界,从而对p取值就说不定了。看出你的本意是按blocks对str求hash值(block大小是一个short),但是在实际指针操作过程有点问题。简单起见,你可以按单字节计算,将p,s指针类型改成unsignedchar×。如果想要实现按blocks计算,可以参考murmurhash方法。···unsignedintmurmur3_32(constchar*key,unsignedintlen,unsignedintseed){staticconstunsignedintc1=0xcc9e2d51;staticconstunsignedintc2=0x1b873593;staticconstunsignedintr1=15;staticconstunsignedintr2=13;staticconstunsignedintm=5;staticconstunsignedintn=0xe6546b64;unsignedinthash=seed;constintnblocks=len/4;constunsignedint*blocks=(constunsignedint*)key;inti;for(i=0;iunsignedintk=blocks[i]; k*=c1;k=(k<>(32-r1)); k*=c2;hash^=k;hash=((hash<>(32-r2)))*m+n; }constchar*tail=(constchar*)(key+nblocks*4);unsignedintk1=0;switch(len&3){case3:k1^=tail[2]<<16;case2:k1^=tail[1]<<8;case1:k1^=tail[0];k1*=c1;k1=(k1<>(32-r1)); k1*=c2;hash^=k1;}hash^=len;hash^=(hash>>16);hash*=0x85ebca6b;hash^=(hash>>13);hash*=0xc2b2ae35;hash^=(hash>>16);returnhash;}
添加回答
举报
0/150
提交
取消