calculate binary to decimal manually

回眸只為那壹抹淺笑 提交于 2021-01-07 06:46:28

问题


assuming I have a function to manually calculate decimal from binary number
*up to four characters(binary)
*assuming you can only input 0 and 1 character

below code works perfectly

function bin_to_dec($bin) {
$bin = str_split($bin);
$bin = array_reverse($bin);

$i = 0;
$dec = 0;
foreach($bin as $values) {
    $ans = $values * pow(2, $i);
    $dec += $ans;
    $i++;
}

return $dec;

}

$bin = 1010 //4
$bin = 1 //1
$bin = 0 //0

assuming if you cannot use function strrev(), str_split(), array_reverse(), how would you convert binary to decimal manually?


回答1:


Well, have you tried the built-in bindec function ?

var_dump(bindec(1010)); // int(10)
var_dump(bindec(1)); // int(1)
var_dump(bindec(101010)); // int(45)

Beware though, this function is meant to be used with strings and can give strange results for ints beginning with 0 :

var_dump(bindec(0101)); // int(0)
var_dump(bindec("0101")); // int(5)



回答2:


http://php.net/manual/en/function.bindec.php

Example bindec() example

<?php
echo bindec('110011') . "\n";
echo bindec('000110011') . "\n";

echo bindec('111');
?>
The above example will output:

51
51
7



回答3:


Try the bindec() function.

$ret_val = bindec("10001101");

this is one simple way,otherwise you can use...

    <?php
function strev($y)
{
for ($x = strlen($y)-1; $x>=0; $x--) {
       $y .= $y[$x];
       $y[$x] = NULL;
}
return $y;
}
function bintodec($str){
    $dec=0;
    $nstr=$str;
    $nstr=strev($nstr);
    for($i=0;$i<strlen($str);$i++){
        $val = ($nstr%pow(10,strlen($nstr)-1)) * pow(2, $i);
        $dec += $val;
        $nstr=floor($nstr/10);
    }
    return $dec;
}
echo bintodec("1111010");
?>



回答4:


Just had to solve this for a student.

  1. Split the string representation into digits
  2. Reverse the digits
  3. Initiate our result
  4. Iterate over all the digits, adding 2 in the power of the index if the digit is a 1

Using the fact that each digit in binary adds 2 in the power of the digits index to the result.

Binary 11 is equal to 2^0 + 2^1 = 3

function binaryToDecimal($str) {
    $digits = str_split($str);
    $reversed = array_reverse($digits);
    $res = 0;

    for($x=0; $x < count($reversed); $x++) {
        if($reversed[$x] == 1) {
            $res += pow(2, $x);
        }
    }

    return $res;
}


来源:https://stackoverflow.com/questions/41760989/calculate-binary-to-decimal-manually

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!