Zend - The PHP Company




Math

Add Code


Base10Converter  

Type: code fragment
Added by: rdickerson
Entered: 08/09/2005
Last modified: 02/12/2005
Rating: - (fewer than 3 votes)
Views: 2849
Convert base 10 int to any other base up to 16. This function will take a take two integer values. The first is the base you want to convert to, the second is the base 10 number you are converting.


<?php 

function convert ($iBase$iNumber)
{
    
$aHexValues = array('0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F');
    
$sReturn '';
    
    
$iIndex 0;
    while (
$iNumber >= $iBase)
    {
        
$iIndex $iNumber $iBase;
        
$iNumber floor($iNumber $iBase);
        
$sReturn $aHexValues[$iIndex] . $sReturn;
    }
    
$sReturn $aHexValues[$iNumber] . $sReturn;
    return 
$sReturn;
}

?>


Usage Example


$iNewBase = 8;
$iBaseTenNum = 21;
$sNewBaseNum = convert($iNewBase, $iBaseTenNum);


printf("Decimal Number: %dn", $iBaseTenNum );
printf("Base Conversion: %dn", $iNewBase );
printf("Converted number is: %sn", $sNewBaseNum );


/* Output ***

Decimal Number: 21 
Base Conversion: 8 
Converted number is: 25

***/


Rate This Script





Search



This Category All Categories