Revision: 39522
Initial Code
Initial URL
Initial Description
Initial Title
Initial Tags
Initial Language
at January 18, 2011 04:15 by kendsnyder
Initial Code
/** * 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 $iToBase = strlen($sToMap); } $sNumber = (string) $sNumber; $length = strlen($sNumber); $result = ''; for ($i = 0; $i < $length; $i++) { $aDigits[$i] = strpos($sFromMap, $sNumber{$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; }
Initial URL
base-convert
Initial Description
Initial Title
Convert a string from one base to another
Initial Tags
convert
Initial Language
PHP