Conversions between decimal point and base 36

I want to convert numbers to base 36 using PHP. The function base_convertdoes not work because I want to convert large numbers: I do not get my starting number if I convert it again from base 36 to decimal.

I tried some function defined on several sites, but I never got the same result. In addition, these two sites (in Javascript) give the same result:

For example, 1010701001118000000000000000you need to convert to 3IZS0ZE1RQ68W8SSW4.

Here are the functions that I tried (and which do not work):

+5
source share
2 answers

Here are two simple functions that use the algorithm found on Wikipedia when using bcmath to get calculations even for very large numbers:

function fromDecimalToBase($in, $to) {
    $in = (string) $in;
    $out = '';

    for ($i = strlen($in) - 1; $i >= 0; $i--) {
        $out = base_convert(bcmod($in, $to), 10, $to) . $out;
        $in = bcdiv($in, $to);
    }

    return preg_replace('/^0+/', '', $out);
}

function fromBaseToDecimal($in, $from) {
    $in = (string) $in;
    $out = '';

    for ($i = 0, $l = strlen($in); $i < $l; $i++) {
        $x = base_convert(substr($in, $i, 1), $from, 10);
        $out = bcadd(bcmul($out, $from), $x);
    }

    return preg_replace('/^0+/', '', $out);
}

However, I get 3izs0ze1rq66tifrpcfor the number you indicated - maybe your conversion was wrong?

+8
source

All Articles