Version: 1.0
Type: Function
Category: Algorithms
License: GNU General Public License
Description: Use to convert a number in any base from 2 to 36 to any other base from 2 to 36. ie: convertBase("FF",16,10) returns 255. You can also use HEX, BINARY, BASE10, DECIMAL and OCT in place of numeric values for the bases. ie: convertBase("FF",HEX,BINARY) returns 11111111.
<?
/****************************************
convertBase($number, $originalBase, $destinationBase);
Author: Chris Heald
Email: cheald45@hotmail.com
Creation date: 1/16/02
License: No restriction, provided this header is left intact. You may
change the purpose if you update the code - leave the author, email,
creation date, license, and changelog intact. You may append to the
changelog as you make changes.
Purpose:
Use to convert a number in any base from 2 to 36 to any other base from 2 to 36.
ie: convertBase("FF",16,10) returns 255. You can also use HEX, BINARY, BASE10, DECIMAL and OCT in place of numeric
values for the bases. ie: convertBase("FF",HEX,BINARY) returns 11111111.
HEX : 16
BASE10 : 10
DECIMAL: 10
OCT : 8
BINARY : 2
Possible future enhancements:
Even more bases supported. We could use lower case and upper case letters as seperate digits, but that could get
confusing. The benefit of this would be a maximum range of 62 bases.
This was an exericse I did in my free time. Please feel free
to expand or enhance it, and feel free to email me if you have questions.
*** Change Log ***
01/16/02 - CMH
Created File. Version 1.00
******************
****************************************/
define("HEX",16);
define("BINARY",2);
define("OCT",8);
define("BASE10",10);
define("DECIMAL", 10);
function convertBase($number, $fromBase = 10, $toBase = 2) {
if($toBase > 36 || $toBase < 2) //check base validity
return "Invalid originating base.";
if($fromBase > 36 || $fromBase < 2)
return "Invalid destination base.";
@list($number, $decimal) = explode(".",$number);
for($i = 0; $i < strlen($number); $i++) { //convert to base 10
$digit = substr($number, $i, 1);
if(eregi("[a-z]",$digit)) {
$x = ord($digit) - 65 + 10;
if($x > $fromBase)
$x -= 32;
$digit = $x;
}
@$base10 += $digit * (pow($fromBase, strlen($number) - $i - 1));
}
$number = $base10;
if($toBase == 10)
return $number;
$q = $number;
while($q != 0) { //convert base 10 equivalent to specified base
$r = $q % $toBase;
$q = floor($q / $toBase);
if($r > 9)
$r = chr(($r - 9) + 64);
@$baseres = "$r" . "$baseres";
}
return $baseres;
}
?>