Convertion from Binary to Decimal
Posted: Tue Nov 11, 2008 5:46 am
hi everyone
that's my first post here .. hope u like it
i've made a function to convert from binary to decimal system
some people might say there is already a built-in one called decbin() ....
but that function doesn't convert fractions ... thats why i made it :
here it is :
i'm ready for any question
bye now
that's my first post here .. hope u like it
i've made a function to convert from binary to decimal system
some people might say there is already a built-in one called decbin() ....
but that function doesn't convert fractions ... thats why i made it :
here it is :
Code: Select all
function BinaryToDecimal($binary){
$binary=trim($binary);
if (strstr($binary,'.')){
$split=explode('.',$binary);
$integer=$split[0];
$fraction=$split[1];
$digits=str_split($fraction);
$num=sizeof($digits);
for ($i=1; $i<=$num;$i++){
if ($digits[$i-1]>1){
echo '<script>alert("Enter Binary Digits Only {0,1}\n \n eg: 11001 or 11001.011");history.go(-1)</script> ';
}
$exponent=pow(2,-$i);
$fraction_result+=$digits[$i-1]*$exponent;
}
}else{
$integer=$binary;
}
$splits=str_split($integer);
$num=sizeof($splits)-1;
$i=$num;
foreach($splits as $digits){
if ($digits>1){
echo '<script>alert("Enter Binary Digits Only {0,1}\n \n eg: 11001 or 11001.011");history.go(-1)</script> ';
}
$exponent=pow(2,$i);
$integer_result+=$digits*$exponent;
$i--;
}
if($fraction_result){
$result=$integer_result+$fraction_result;
}else {
$result=$integer_result;
}
return $result ;
}
bye now