How to convert binary number to decimal in PHP

1 Answer

0 votes
function binary_to_decimal($s) { 
    $dec = 0;
   
    for ($i = strlen($s) - 1, $j = 0; $i >= 0; $i--, $j++) { 
        if ($s[$i] == '1') {
            $dec += pow(2, $j); 
        }
    } 
    return $dec; 
} 
     
$s = "10101011";  
   
echo binary_to_decimal($s); 
  
  
  
/*
run:
       
171
      
*/

 



answered May 10, 2019 by avibootz

Related questions

2 answers 367 views
1 answer 258 views
258 views asked Nov 20, 2017 by avibootz
1 answer 225 views
2 answers 272 views
1 answer 206 views
206 views asked Dec 31, 2020 by avibootz
2 answers 347 views
...