1

My code is like this :

<?php

function binary_to_decimal($a) {
    $bin_array = str_split($a);

    $y=sizeof($bin_array)-1;
    for ($x=0; $x<sizeof($bin_array)-1; $x++) {
        if ($bin_array[$x] == 1) {
            $bin_array[$x] = bcpow(2, $y);
        }
        $y--;
    }

    for ($z=0; $z<sizeof($bin_array); $z++) {
        $result = bcadd($result, $bin_array[$z]);
    }
    echo $result;
}

binary_to_decimal('11111');

?>

It still using PHP native functions. For example : bcpow, sizeof, bcadd.

Whether it can convert binary to decimal without using PHP native functions?

Thank you

2
  • php.net/manual/en/function.bindec.php in php exist function for this if I don't wrong bindec Commented Apr 20, 2016 at 10:59
  • He doesn't want to use native functions. Commented Apr 20, 2016 at 11:02

1 Answer 1

1

Here is in http://php.net/manual/en/function.bindec.php#44910

function reconvert($bin_nr) {
 $base=1;
 $dec_nr=0;
 $bin_nr=explode(",", preg_replace("/(.*),/", "$1", str_replace("1", "1,", str_replace("0", "0,", $bin_nr))));
 for($i=1; $i<count($bin_nr); $i++) $base=$base*2;
 foreach($bin_nr as $key=>$bin_nr_bit) {
     if($bin_nr_bit==1) {
         $dec_nr+=$base;
         $base=$base/2;
     }
     if($bin_nr_bit==0) $base=$base/2;
 }
 return(array("string"=>chr($dec_nr), "int"=>$dec_nr));
}

Check here : https://eval.in/556903

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.