/ Published in: PHP
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
/** * Convert a string to a string in another base * * Note: based on http://php.net/manual/en/function.base-convert.php#55204 * Note: the bases are only limited to the length of $sFromMap and $sToMap and $sNumber can be any length * * @param string $sNumber the number which to convert * @param int $iFromBase the base from which to convert * @param int $iToBase the base to which to convert * @param string $sFromMap the ascii string to decode the string * @param string $sTomMap the ascii string to encode the string * @return string */ function baseConvertString($sNumber, $iFromBase, $iToBase = null, $sFromMap = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_", $sToMap = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_" ) { if ($iToBase === null) { // use the max } $sNumber = (string) $sNumber; $result = ''; for ($i = 0; $i < $length; $i++) { } do { // Loop until whole number is converted $divide = 0; $newlen = 0; for ($i = 0; $i < $length; $i++) { // Perform division manually (which is why this works with big numbers) $divide = $divide * $iFromBase + $aDigits[$i]; if ($divide >= $iToBase) { $aDigits[$newlen++] = (int)($divide / $iToBase); $divide = $divide % $iToBase; } elseif ($newlen > 0) { $aDigits[$newlen++] = 0; } } $length = $newlen; $result = $sToMap{$divide} . $result; // Divide is basically $sNumber % $iToBase (i.e. the new character) } while ($newlen != 0); return $result; }
URL: base-convert