Skip to content

Instantly share code, notes, and snippets.

@LoneFry
Created September 27, 2012 03:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LoneFry/3792021 to your computer and use it in GitHub Desktop.
Save LoneFry/3792021 to your computer and use it in GitHub Desktop.
Convert numbers up to base73
<?php
/**
* Convert a number from one base to another
* Modelled after PHP's base_convert(), but able to handle base73
*
* @param string $num The number to convert
* @param int $from The base from which to convert
* @param int $to The base to which to convert
*
* @return string The converted number
*/
function base_convert_($num, $from, $to) {
//Character set of a base-_ number
//Characters chosen as those valid and unreserved in a URL
//Characters higher than 62 not expected to match other base_convert implementations
$chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$-_.+!*\'(),';
//Validate the `from' and `to' bases supplied
if ($from < 2 || strlen($chars) < $from) {
trigger_error("base_convert_(): Invalid `from base' ($from)", E_USER_WARNING);
return null;
}
if ($to < 2 || strlen($chars) < $to) {
trigger_error("base_convert_(): Invalid `to base' ($to)", E_USER_WARNING);
return null;
}
//to mimic the functionality of PHP's base_convert, strip characts exceeding `from base'
$num = preg_replace('/[^'.substr($chars,0,$from).']/','',strrev($num.''));
//if `from base' is 36 or less, ignore case
if (36 <= $from) {
$num = strtolower($num);
}
//convert supplied number to an int
$value = 0;
for ($i = strlen($num)-1; $i >= 0; $i--) {
$digit = strpos($chars, $num[$i]);
if ($from <= $digit) {
trigger_error("base_convert_(): Invalid number supplied, digit ($digit) exceeds `from base' ($from)", E_USER_WARNING);
}
$value += $digit * pow($from, $i);
}
//convert intermediate int to desired base
$result = '';
do {
$result = $chars[intval($value % $to)].$result;
} while (0 < $value = floor($value / $to));
return $result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment