How to get a 64 bit integer hash from a string in

2019-07-07 03:13发布

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

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

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.

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

5条回答
兄弟一词,经得起流年.
2楼-- · 2019-07-07 03:53

See this page for info on an md5 hash :

http://us.php.net/manual/en/function.md5.php

This will output a 32 char hex string. Each hex char represents 4 bits of data. this means you need 16 hex chars (or half the md5 hash) to generate 64 bits.

you can then use hexdec to convert the 64 bits (16x4=64) from hex to an int. Note if you pas more than 64 bits the function will overflow to the float type to try to represent the larger number

http://php.net/hexdec

So basically

$stringToHash= "abcdefghijk...";
$hash = md5($stringToHash);
$substring = substr($hash, 0,16);
$finalInt = hexdec($substring);

That should work for you. (but i haven't tested it).

查看更多
戒情不戒烟
3楼-- · 2019-07-07 04:00

PHP doesn't support 64 bits integers I think. There is a BigInteger class (not native PHP) that you could use (and find if you Google really well). But it just uses strings internally and it's hella complex.

查看更多
三岁会撩人
4楼-- · 2019-07-07 04:03

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];
}

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.

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).

查看更多
仙女界的扛把子
5楼-- · 2019-07-07 04:05
地球回转人心会变
6楼-- · 2019-07-07 04:11

If nobody else has a better idea, you can probably modify murmurhash_php to invoke the 64-bit version of MurmurHash3 pretty easily.

查看更多
登录 后发表回答