Welcome Guest, Not a member yet? Register   Sign In
fastest way to hash a string in an int
#1

[eluser]gungbao[/eluser]
Hi Coders,

I am looking for PHPs fastest way to convert a string of an arbitrary length into ... not an md5 but a positive integer, not a unique one but the same string needs to end up always to the same integer. lets say, similar to md5 but without any characters but only digits in the hash.

Anyone an idea for a solution faster than grepping/replacing all numbers from a resulting md5?

Have fun to think about it Smile would help me a lot.
Thanks in advance for any idea,
Chris
#2

[eluser]pistolPete[/eluser]
First of all, why do you need a integer hash?

You can use e.g.:
Code:
echo abs(crc32("test string"))

Or build one on your own (but I did compare the speed):

Code:
function integer_hash($string)
{
    // could be any seed instead of 0
    $hash = 0;
    $length = strlen($string);
    for($i=0; $i < $length; $i++)
    {
        // this one is _very_ simple:
        // add up ascii value of characters
        $hash += ord($string[$i]);
        
        // alternatively, a better hash "quality"
        // can be produced using the following:
        // multiply by a prime and add ascii value of character
        $hash = $hash * 101 + ord($string[$i]);
    }
    return $hash;
}

If you need some more advanced algorithms, have a look at http://vak.ru/doku.php/proj/hash/sources.
They are written in C but can easily be transformed into PHP.
#3

[eluser]gungbao[/eluser]
Hola pistolPete,

many thanks for the very interesting links about hashing algorithms.

Code:
abs(crc32($s));

does it perfectly.

Profiling over 10.000 iterations:

abs(crc32($s)) : 0.012081sec
fn integer_hash(): 1.645170 sec
fn md5(): 0.017706sec

Code:
$pattern = '/[a-z]/i';
    $replacement = '';
    $n = preg_replace($pattern, $replacement, md5($s));

runs with 0.077064


Many thanks for your help!
Cheers,
Chris




Theme © iAndrew 2016 - Forum software by © MyBB