关于C溢出,如何在Python中使用64位无符号整数数学?
我正在尝试用Python实现哈希 这里是C:关于C溢出,如何在Python中使用64位无符号整数数学?,python,hash,integer,unsigned,Python,Hash,Integer,Unsigned,我正在尝试用Python实现哈希 这里是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
/* 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;
}
/*djb2散列http://www.cse.yorku.ca/~oz/hash.html*/
uint64\u t djb2(大小长度,字符常量长度[len]){
uint64_t hash=5381;
uint8_t c;
对于(大小i=0;i hash=((hash您可以在纯Python中非常轻松地实现由C代码运行的算法,而不需要任何ctypes
内容。只需使用常规Python整数完成所有操作,并在最后取一个模(高位不会影响您正在执行的操作的低位):
正如我在代码中所评论的,由于这是一个在ByTestRing上定义的操作,您应该使用字节
实例作为参数。请注意,此算法有许多不同的实现。有些使用^
(按位异或)与更新哈希值的步骤中的+
不同,它通常被定义为使用无符号长
,该长
通常是32位,而不是问题中C版本使用的显式64位整数。我将用相应的ctypes int对象替换所有int
对象。例如0xFFFFFFFFFFFFFF
是Pythonint
对象。你能给出一个你得到错误答案的字符串示例吗?谢谢!在这种情况下,我同时控制C和Python实现,所以64位是我想要的,但对于遇到这个问题的其他人来说,这是一个极好的观点。
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
def djb2(string: bytes) -> int: # note, use a bytestring for this, not a Unicode string!
h = 5381
for c in string: # iterating over the bytestring directly gives integer values
h = h * 33 + c # use the computation from the C comments, but consider ^ instead of +
return h % 2**64 # note you may actually want % 2**32, as this hash is often 32-bit