Posts Tagged ‘binary’

Binary to Decimal Conversion

21. May 2009

No Comments »

Converts a binary number to its decimal equivalent. However unlike the bindec function, this will preserve the binary/radix point.

Code

<?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

Usage

echo bin2dec ( "1011101.1000101");

Output

93.5390625