如何从一个字符串在PHP中的64位整数哈希?整数、字符串、PHP

2023-09-09 21:17:28 作者:等你到地老天荒

我需要串的64位整数哈希像哈希映射。

I need 64 bit integer hashes of strings for something like a hash map.

在我看来,像有没有原生的PHP哈希功能,可以返回64位整数?

It seems to me like there is no native PHP hash functionality that can return 64 bit integers?

我认为这是可能采取SHA1哈希的第一部分,并将其转换为整数。但是这不会带来最佳的性能和转换似乎是棘手的。

I think it is possible to take the first part of a sha1 hash and convert it to an integer. However that will not bring the best performance and the conversion seems to be tricky.

当然,这将是很好用PHP函数没有安装。

Of course it would be nice to use native PHP functions without installations.

推荐答案

我尝试了很多,尤其是完整的64位十六进制字符串转换为符号的64位整数。现在,我结束了这一点:

I tried a lot, especially to convert a full 64 bit hex string to an signed 64 bit integer. Now I ended up with this:

function sha1_64bitInt($str) {
    $u = unpack('N2', sha1($str, true));
    return ($u[1] << 32) | $u[2];
}

性能则介于中间。很多比实现一个完整的哈希算法(如SimpleHash或dbj2)和很多比赤裸裸调用慢于 SHA1() CRC32 。

当会有一次更好的解决方案转换为64位整数将有可能改善这一功能,而不会破坏向后兼容性(我希望)。

When there will be once a better solution to convert to a 64 bit integer it will be possible to improve this function without breaking backwards compatibility (I hope).