Search code examples
intnumericalphanumeric

Convert AlphaNumeric To Numeric And Should Be An Unique Number


I want to convert an alphanumeric(string) value to numeric(int). alphanumeric values like 'af45TR'. I wanted that numeric(int) value should be unique and it should not go out of the size of int like 64, 32 bits. How can i do that?.


Solution

  • If you consider the string to be a number in base 62, you could write a function to perform a base conversion from base 62 to base 10. An example in PHP could be;

    function base62toDec($n)
    {
        $vals = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $vals = array_flip(str_split($vals));
        $out = 0;
        $len = strlen($n);
        for ($i = 0; $i < $len; $i++) {
            $c = $n[$len - ($i + 1)];
            $out += $vals[$c] * pow(62, $i);
        }
        return $out;
    }
    
    echo base62toDec('af45TR'); // outputs 9383949355