简体   繁体   中英

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

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.

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

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM