S
S
SiD152017-08-02 11:54:22
PHP
SiD15, 2017-08-02 11:54:22

What would the method look like in C# System.String.GetHashCode() in PHP?

Trying to get the same hash in PHP as in this example rextester.com/JGN30101
Went to look at the System.String.GetHashCode() method in the Reference Source
Is it possible to rewrite it in PHP?
It is necessary that hash be -2038622410
In search of a solution, I found functions in PHP similar to hashCode in Java, but the result is different

function hashCode64($str) {
    $str = (string)$str;
    $hash = 0;
    $len = strlen($str);
    if ($len == 0 )
        return $hash;
 
    for ($i = 0; $i < $len; $i++) {
        $h = $hash << 5;
        $h -= $hash;
        $h += ord($str[$i]);
        $hash = $h;
        $hash &= 0xFFFFFFFF;
    }
    return $hash;
}

function hashCode32( $s )
{
    $h = 0;
    $len = strlen($s);
    for($i = 0; $i < $len; $i++)
    {
        $h = overflow32(31 * $h + ord($s[$i]));
    }

    return $h;
}

function overflow32($v)
{
    $v = $v % 4294967296;
    if ($v > 2147483647) return $v - 4294967296;
    elseif ($v < -2147483648) return $v + 4294967296;
    else return $v;
}

if(PHP_INT_SIZE === 4)
{
   echo hashCode32('KD6267330');  // -1999504710
} else {
   echo hashCode64('KD6267330');  // 2295462586
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
F
Fortop, 2017-08-02
@SiD15

It's actually not recommended to do this
https://msdn.microsoft.com/en-us/library/system.ob...
You should not assume that equal hash codes imply object equality.
You should never persist or use a hash code outside the application domain in which it was created , because the same object may hash across application domains, processes, and platforms.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question