它在C中:
/* djb2 hash http://www.cse.yorku.ca/~oz/hash.html */
uint64_t djb2(size_t len,char const str[len]) {
uint64_t hash = 5381;
uint8_t c;
for(size_t i = 0; i < len; i++) {
c = str[i];
hash = ((hash << 5) + hash) + c; /* hash * 33 + c */
}
return hash;
}
这是我在Python中的尝试:
from ctypes import c_uint64,c_byte,cast,POINTER
def djb2(string: str) -> c_uint64:
hash = c_uint64(5381)
raw_bytes = cast(string,POINTER(c_byte * len(string)))[0]
for i in range(0,len(raw_bytes)):
hash = c_uint64((((((hash.value << 5) & 0xffffffffffffffff) + hash.value) & 0xffffffffffffffff) + raw_bytes[i]) & 0xffffffffffffffff) # hash * 33 + c
return hash
但是,我在两者之间得到了不同的结果,我怀疑是由于不同的溢出行为或其他数学上的差异.
在python版本中屏蔽的原因是试图强制溢出(基于this answer).