I need a base_convert() function that works from base 2 to base 62, but I don’t have the math I need to use, I know that due to PHP limitations I need to use bcmath, which is good.
Functions like they convert a number to a base and from base 10 to another base to 62, but I want to implement the same base_convert() functionality, for example: the only function that can convert between arbitrary bases.
I found a function that seems to do this , but it gives me the feeling of having redundant and slow code, and I would kind of fine-tune it if I know German that I don’t have. = (
Here is a more readable version of the function:
function bc_base_convert($value, $quellformat, $zielformat) { $vorrat = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; if (min($quellformat, $zielformat) < 2) { trigger_error('Bad Format min: 2', E_USER_ERROR); } if (max($quellformat, $zielformat) > strlen($vorrat)) { trigger_error('Bad Format max: ' . strlen($vorrat), E_USER_ERROR); } $dezi = '0'; $level = 0; $result = ''; $value = trim(strval($value), "\r\n\t +"); $vorzeichen = '-' === $value{0} ? '-' : ''; $value = ltrim($value, "-0"); $len = strlen($value); for ($i = 0; $i < $len; $i++) { $wert = strpos($vorrat, $value{$len - 1 - $i}); if (FALSE === $wert) { trigger_error('Bad Char in input 1', E_USER_ERROR); } if ($wert >= $quellformat) { trigger_error('Bad Char in input 2', E_USER_ERROR); } $dezi = bcadd($dezi, bcmul(bcpow($quellformat, $i), $wert)); } if (10 == $zielformat) { return $vorzeichen . $dezi; // abkürzung } while (1 !== bccomp(bcpow($zielformat, $level++), $dezi)); for ($i = $level - 2; $i >= 0; $i--) { $factor = bcpow($zielformat, $i); $zahl = bcdiv($dezi, $factor, 0); $dezi = bcmod($dezi, $factor); $result .= $vorrat{$zahl}; } $result = empty($result) ? '0' : $result; return $vorzeichen . $result; }
Can someone explain to me the above function or give me some lights about the process of direct conversion between arbitrary databases?
math php base-conversion base62
Alix axel
source share