Assign a number (1 to 9) to the md5 hash

The presence of the md5 hash, for example:

md5("test") = "098f6bcd4621d373cade4e832627b4f6"

How can I write a function to return a number from 1 to 9 every time I pass the md5 hash? The number must always be the same, i.e. Myfunc ("098f6bcd4621d373cade4e832627b4f6") should always return the same number. Thank you for your help.

+3
source share
6 answers

This is a WAY reboot, and a suggestion to return the leftmost digit is the best ...

function myfunc($md5) {
    $total = 0;
    foreach (str_split($md5) as $char) $total += ord($char);
    return $total % 9 + 1;
}

echo myfunc("098f6bcd4621d373cade4e832627b4f6");

This way you can easily change the range of return values ​​that interest you by changing the return status.

Or a more compact version:

function myfunc2($md5) {
    return array_sum(array_map("ord", str_split($md5))) % 9 + 1;
}

You can even pass min and max as args:

function myfunc2($md5, $min = 1, $max = 9) {
    return array_sum(array_map("ord", str_split($md5))) % $max + $min;
}

myfunc2("098f6bcd4621d373cade4e832627b4f6", 10, 20);
+5
source

: md5 :) . , , , ( ).

+4

Return 1 all the time. Meets the specification!

More importantly, what do you need for this number?

+3
source

Return the left digit (in 1..9, of course) to the hash considered as a string.

Or am I missing a point?

+2
source

You essentially want the hash function of your hash function. This will be some psedo code:

int hashhash(string hash)
    return (hash[0] % 9) + 1;
+2
source

Here's the solution:

return substr(base_convert($md5, 16, 9), -1) + 1;

This is what you probably want, although you did not say that.

+1
source

Source: https://habr.com/ru/post/1770737/


All Articles