Convert a string from one base to another


/ Published in: PHP
Save to your folder(s)



Copy this code and paste it in your HTML
  1. /**
  2.  * Convert a string to a string in another base
  3.  *
  4.  * Note: based on http://php.net/manual/en/function.base-convert.php#55204
  5.  * Note: the bases are only limited to the length of $sFromMap and $sToMap and $sNumber can be any length
  6.  *
  7.  * @param string $sNumber the number which to convert
  8.  * @param int $iFromBase the base from which to convert
  9.  * @param int $iToBase the base to which to convert
  10.  * @param string $sFromMap the ascii string to decode the string
  11.  * @param string $sTomMap the ascii string to encode the string
  12.  * @return string
  13.  */
  14. function baseConvertString($sNumber, $iFromBase, $iToBase = null,
  15. $sFromMap = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_",
  16. $sToMap = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_"
  17. ) {
  18. if ($iToBase === null) {
  19. // use the max
  20. $iToBase = strlen($sToMap);
  21. }
  22. $sNumber = (string) $sNumber;
  23. $length = strlen($sNumber);
  24. $result = '';
  25. for ($i = 0; $i < $length; $i++) {
  26. $aDigits[$i] = strpos($sFromMap, $sNumber{$i});
  27. }
  28. do { // Loop until whole number is converted
  29. $divide = 0;
  30. $newlen = 0;
  31. for ($i = 0; $i < $length; $i++) { // Perform division manually (which is why this works with big numbers)
  32. $divide = $divide * $iFromBase + $aDigits[$i];
  33. if ($divide >= $iToBase) {
  34. $aDigits[$newlen++] = (int)($divide / $iToBase);
  35. $divide = $divide % $iToBase;
  36. } elseif ($newlen > 0) {
  37. $aDigits[$newlen++] = 0;
  38. }
  39. }
  40. $length = $newlen;
  41. $result = $sToMap{$divide} . $result; // Divide is basically $sNumber % $iToBase (i.e. the new character)
  42. } while ($newlen != 0);
  43. return $result;
  44. }

URL: base-convert

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.