Skip to content
Advertisement

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.

Advertisement

Answer

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

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement