Conversion de Numeros
Posted on February 6th, 2007 in Código, Php |
Permite convertir numero de una base a otra
PHP:
-
<?
-
/****************************************
-
convertBase($number, $originalBase, $destinationBase);
-
-
Author: Chris Heald
-
Creation date: 1/16/02
-
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.
-
-
****************************************/
-
-
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.";
-
-
for($i = 0; $i <strlen($number); $i++) {
-
//convert to base 10
-
if($x> $fromBase)
-
$x -= 32;
-
$digit = $x;
-
}
-
}
-
$number = $base10;
-
if($toBase == 10)
-
return $number;
-
$q = $number;
-
while($q != 0) {
-
//convert base 10 equivalent to specified base
-
$r = $q % $toBase;
-
if($r> 9)
-
@$baseres = "$r" . "$baseres";
-
}
-
return $baseres;
-
}
-
-
?>
Popularidad: 16%

