【问题标题】:How to convert binary to decimal without using PHP native functions?如何在不使用 PHP 本机函数的情况下将二进制转换为十进制?
【发布时间】:2016-04-20 19:10:40
【问题描述】:

我的代码是这样的:

<?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');

?>

它仍然使用 PHP 原生函数。例如:bcpow、sizeof、bcadd。

不使用PHP原生函数是否可以将二进制转十进制?

谢谢

【问题讨论】:

标签: php


【解决方案1】:

这里是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));
}

在这里查看:https://eval.in/556903

【讨论】:

    猜你喜欢
    • 2014-05-26
    • 2015-06-09
    • 2010-12-05
    • 2019-03-22
    • 2021-12-27
    • 1970-01-01
    • 2019-07-10
    • 1970-01-01
    相关资源
    最近更新 更多