zoukankan      html  css  js  c++  java
  • 2/8/16 转10进制

    <?php 
    /*
     * 二进制、八进制、十六进制转十进制
     * @params $data 将该二进制数转10进制 $decimal 指定传进来的是几进制的数
     */
     function tDecimal($data, $decimal){
         //如果为空直接返回
         if(empty($data) && empty($decimal)){
             return ;
         }
        
        $arr = array("0b"=>2,"0"=>8,"0x"=>16);
        $remainderArr = array(10=>'a', 11=>'b', 12=>"c", 13=>'d', 14=>"e", 15=>"f");
        $remainderArr_rev = array_flip($remainderArr);
    
        if(!in_array($decimal, $arr)){
            return ;
        }
        
        $newData = (string)$data;    //强制转化为字符串
    
        $num = 0;
        $len = strlen($newData);
        for($i=0;$i<$len;$i++){
            if($decimal == 16 && in_array($newData[$i], $remainderArr)){
                $num += $remainderArr_rev[$newData[$i]]*pow($decimal,$len-$i-1);
            }else{
                $num += $newData[$i]*pow($decimal,$len-$i-1);
            }
        }
    
        return $num;
     }
     
    var_dump(tDecimal("101", 2));    //int(5) 
    var_dump(tDecimal("07", 8));    //int(7)
    var_dump(tDecimal("1f", 16));    //int(31)
  • 相关阅读:
    POJ 2057 The Lost House
    SRM 597
    poj3020(Antenna Placement)
    poj3041(Asteroids)
    poj2388(Who's in the Middle)
    poj3687(Labeling Balls)
    poj1094(Sorting It All Out)
    poj3026(Borg Maze)
    poj1258(Agri-net)
    poj2485(Highways)
  • 原文地址:https://www.cnblogs.com/yuwensong/p/5139402.html
Copyright © 2011-2022 走看看