PHP internal hashCode Function

后端 未结 5 704
孤独总比滥情好
孤独总比滥情好 2021-02-09 14:59

I am looking for the PHP equelent to JAVA\'s

 \"SomeString\".hashCode();

function. The hashCode i am looking for should be the same which is u

5条回答
  •  再見小時候
    2021-02-09 15:05

    Here is my 2 cents for implementing Java's hashCode in PHP:

    /**
     * Simulates java hashCode function
     * hash a string to 32 bit
     * @param str the string to hash
     * @return hashed 32 bit integer
     */
    function hashCode($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;
    };
    

提交回复
热议问题