Yoone - 11 months ago 65

PHP Question

I want to convert numbers in base 36 using PHP. The function

`base_convert`

I tried some function given on multiple websites, but I never get the same result. Also, these two websites (in Javascript) give the same result:

- http://www.unitconversion.org/numbers/base-10-to-base-36-conversion.html
- http://www.translatorscafe.com/cafe/units-converter/numbers/calculator/decimal-to-base-36/

For example

`1010701001118000000000000000`

`3IZS0ZE1RQ68W8SSW4`

Here are the functions I tried (and which don't work):

- http://www.php.net/manual/fr/function.base-convert.php#34510
- http://www.php.net/manual/fr/function.base-convert.php#106546
- http://www.tonymarston.net/php-mysql/showsource.php?file=converter.php
- http://www.geoffray.be/blog/php/convertir-des-nombres-en-base-62

Answer Source

Here are two simple functions using an algorithm found on Wikipedia, while using bcmath to get the calculations even for very large numbers right:

```
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 `3izs0ze1rq66tifrpc`

for the number you've provided - maybe your conversion was wrong there?