0

Let's say I have a database of 100,000 more or less random strings and I want to generate a number from each string between 1 and 500.

My method should always generate the same number (given the same string) and it should be an even distribution of numbers from 1 to 500.

Any ideas?

2
  • You're looking for your own string encoding method? :o Commented Mar 21, 2013 at 9:39
  • 2
    Use a CRC (PHP's crc32() function - php.net/manual/en/function.crc32.php), then adjust the result to fit your range Commented Mar 21, 2013 at 9:40

2 Answers 2

1

Seems like you need a hashing function. You can use crc32 and modulus operator:

echo abs(crc32("hello world")) % 500 + 1;
Sign up to request clarification or add additional context in comments.

1 Comment

Please note that crc32() returns a signed integer and thus it can be -1234567. For use in my case adding abs() around the crc32() function did the trick
0

You could also use something like:

function string_to_decimal($hex_str)
{
    $arr = str_split($hex_str, 4);
    foreach ($arr as $grp) {
        $dec[] = str_pad(hexdec($grp), 5, '0', STR_PAD_LEFT);
    }
    return implode('', $dec);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.