1

This problem is similar to: How to get a 64 bit integer hash from a string in PHP?

I have this JAVA function. I would like to have the same function in PHP. thanks

/**
 * returns the first 64 bits of the md5 digest as a long
 */
public static long get64BitMD5(String text) {
    try {
        MessageDigest md = MessageDigest.getInstance("MD5");
        md.update(text.getBytes(UTF_8));
        byte [] digest = md.digest();
        long ret = 0;
        for (int i = 0; i < 8; i++)
            ret = (ret<<8)|(((long)digest[i])&0xFFl);
        return ret;
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }
}
Community
  • 1
  • 1
Yada
  • 30,349
  • 24
  • 103
  • 144

2 Answers2

1

This is possible using bcmath plus some extensions from a comment in the accepted answer here: Using bit operations on 64 bits integers in 32 bit systems (no php_gpm extension). You'll also need the bchexdec() function from here: http://www.php.net/manual/en/ref.bc.php#99130

So, if you include what can be found at http://www.nirvani.net/software/bc_bitwise/bc_bitwise-0.9.0.inc.php.asc, you can use the following function.

function get64BitMD5($stringToHash) {
    $hash = md5($stringToHash, true);
    $ret = '0';
    for ($i = 0; $i < 8; $i++) {
        $char = substr($hash, $i, 1); 
        $ret = bcmul($ret, '256'); // (ret<<8)
        $tmp = unpack('c', $char); 
        $tmp = $tmp[1] & 0xFF;
        $ret = bcor($ret, $tmp); // bitwise OR ( | op)
    }

    if (bccomp($ret, '9223372036854775807') == 1) { // > 0x7FFFFFFFFFFFFFFF
        $ret = bcsub($ret, bchexdec('10000000000000000'));
    }

    return $ret;
}
Community
  • 1
  • 1
ndwhelan
  • 38
  • 4
1

You cannot do this in base PHP, because PHP has no 64-bit integer type (echo PHP_INT_SIZE for confirmation). It might have a 64-bit signed integer type if you are running on a x64 stack, but there's no guarantee.

There are extensions that provide arbitrary-sized integer types, but those are going to be unwieldy if you want to perform bitwise arithmetic.

What are you trying to accomplish? Surely there's some other way you can achieve your aim.

Jon
  • 428,835
  • 81
  • 738
  • 806
  • 64-bit PHP does have 64-bit signed integer, but not 64-bit unsigned integer... but it would be possible to calculate a 64-bit bytestream – Mark Baker Jan 17 '12 at 00:30
  • @MarkBaker: It is [trivial](http://www.php.net/manual/en/function.pack.php) to convert the hex output of `md5` to raw bytes if that's what the OP wants. The only problem is that they aren't telling. – Jon Jan 17 '12 at 00:34