Please tell me how you can implement the conversion of a number from a binary number system to a decimal, so that it is recorded as the sum of the degrees of the binary number system to the corresponding number in the system discharge.

What you need to add

<?php $i = '101'; function myBin2Dec($i) { sum k[i](2^(i)); i = {0; ->} //направление разбора строки с представленным двоичным числом, с права на лево. где i элемент последовательности. k значение iго элемента echo "=======\n<br>i = ".i."; base = 10\n</br>=======</br>"; } $result = myBin2Dec($i); echo "result = ".$result."\n</br>"; ?> 
  • sum k [i] * (2 ^ (i)); i = {0; ->} the direction of parsing the string with the represented binary number, from right to left. where i is an element of the sequence. k value of item i. example 1101 <-; 1 * (2 ^ 0) + 0 * (2 ^ 1) + 1 * (2 ^ 2) + 1 * (2 ^ 3) = 1 + 4 + 8 = 13 - vv2cc
  • And how do I write this in the script? - andrey26rus
  • What you need to add here is <? Php $ i = '101'; function myBin2Dec ($ i) {sum k [i] (2 ^ (i)); i = {0; ->} // direction of parsing the string with the represented binary number, from right to left. where i is an element of the sequence. k value of element i of echo "======= \ n <br> i =" .i. "; base = 10 \ n </ br> ======= </ br>"; } $ result = myBin2Dec ($ i); echo "result =". $ result. "\ n </ br>"; ?> - andrey26rus

1 answer 1

Something like that, without any special checks ...

 <?php $input = '1101'; function bin2dec($data) { $result_dbg = ""; $result = 0; $dataLen = strlen($data); for($i = 0, $sh = $dataLen; $i < $dataLen; $i++, $sh--){ $elem = (int) substr($data, $sh - 1, 1); $result_dbg .= "$elem*(2^$i) "; $result += $elem * pow(2, $i); } $result_dbg .=" = $result"; print ( $result_dbg ); return $result; } bin2dec($input); ?> 

Result: 1 (2 ^ 0) 0 (2 ^ 1) 1 (2 ^ 2) 1 (2 ^ 3) = 13