<?php
/**
* Convert a binary number with our without
* a radix point to its decimal equivalent.
*
* @param $binary The binary number to convert.
* @param $output Show the calculations.
* @return The decimal conversion
*/
function bin2dec($binary, $output = false) {
$N = 0;
$o = "";
list ( $rhs, $lhs ) = explode ( ".", $binary );
$rhs = strrev ( $rhs );
for($i = 0; $i < strlen ( $rhs ); $i ++) {
$d = $rhs [$i] * pow ( 2, $i );
$N = $d + $N;
$o = ($d == 0) ? $o : $o . $d . " + ";
}
for($i = 0; $i < strlen ( $lhs ); $i ++) {
$d = $lhs [$i] * pow ( 2, - ($i + 1) );
$N = $d + $N;
$o = ($d == 0) ? $o : $o . $d . " + ";
}
return ($output) ? substr ( $o, 0, - 3 ) . " = " . $N : $N;
}
?>
Usage:
echo bin2dec ( "1011101.1000101", true );Output:
1 + 4 + 8 + 16 + 64 + 0.5 + 0.03125 + 0.0078125 = 93.5390625


Sign In
Create Account

Back to top










