How to convert binary to decimal without basic functions?

Hi everyone! Here is my task to translate from binary midrange to decimal. For example 1001 = 9 in decimal. Here I found the standard function convert_basic (), but unfortunately the standard function cannot be used in the task. Who will help, I will be very grateful.


Answer 1, authority 100%

function mybindec($bin) {
  $n = 1;
  $dec = 0;
  $bin = (string)$bin;
  for ($i = strlen($bin)-1; $i >= 0; $i--) {
    if ($bin{$i}=="1") $dec = $dec + $n;
    $n = $n * 2;
    }
  return $dec;
  }

I hope INT is fine? those. whole numbers. FLOAT is a little more difficult.


Answer 2, authority 33%

you can do this

function mybindec($bin) {
  $n   = 0;
  $dec = 0;
  $bin = (string)$bin;
  $len = strlen($bin);
   while($len>=$n){
     if(intval(substr($bin,$n,1))) $dec += pow(2,$len-$n-1); 
     $n++;
   }
  return $dec;
 }

Answer 3, authority 33%

I’ll do my bit.

function bin2dec($bin) {
    $index = strlen($bin) - 1;
    $result = 0;
    $mult = 1;
    while ($index >= 0) {
            $result += ($bin[$index--] == '1' ? $mult : 0);
            $mult <<= 1;
    }
    return $result;

}


Answer 4

In my opinion, the author needed something like this:

function bin2oct($s_bin){
    $digit = array("000"=>"0", "001"=>"1", "010"=>"2", "011"=>"3", "100"=>"4", "101"=>"5", "110"=>"6", "111"=>"7");
    if($i=strlen($s_bin)%3) $s_binary = str_repeat("0", 3-$i) . $s_bin;
    $s_octal = "";
    for ($i=strlen($s_binary); $i>0; $i-=3) $s_octal = $digit[substr($s_binary,$i-3,3)] . $s_octal;
    return "0".$s_octal;
}
$s_bin = "1001";
sscanf(bin2oct($s_bin), "%o", $num);
$string_dec = sprintf("%d", $num);
printf("binary=%s decimal=%s", $s_bin, $string_dec);