如何从 PHP 中的字符串获取 64 位整数哈希? [英] How to get a 64 bit integer hash from a string in PHP?

查看:62
本文介绍了如何从 PHP 中的字符串获取 64 位整数哈希?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要字符串的 64 位整数哈希值来实现哈希映射之类的东西.

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

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

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 的裸调用要慢得多.

The performance is somewhere in the middle. A lot better than implementing a full hash algorithm (like SimpleHash or dbj2) and a lot slower than a naked call to sha1() or 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).

这篇关于如何从 PHP 中的字符串获取 64 位整数哈希?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆