十進位制轉化為2/8/16

wensongyu發表於2016-01-18
<?php 
/*
 * 十進位制轉二進位制、八進位制、十六進位制
 * @params $data 將哪個十進位制數轉化,  $decimal 轉成哪個進位制,$decimal=2/8/16
 */
 function decimalT($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");

    if(!in_array($decimal, $arr)){
        return ;
    }
    
    $data = intval($data);    //轉化為整形
    $remainder = 0;
    $remainderStr = ``;
    
    
    $remainder = ($data%$decimal) == 0?0:$data%$decimal;
    if($decimal == 16 && $remainder>=10){
        $remainderStr .= $remainderArr[$remainder];
    }else{
        $remainderStr .= $remainder;
    }
    
    $temp = intval($data/$decimal);
    while($temp != 0){
        $remainder = ($temp%$decimal) == 0?0:($temp%$decimal);
        if($decimal == 16 && $remainder>=10){
            $remainderStr .= $remainderArr[$remainder];
        }else{
            $remainderStr .= $remainder;
        }
        $temp = intval($temp/$decimal);
    }
    
    $newArr = array_flip($arr);
    return $newArr[$decimal].strrev($remainderStr);
 }
 
 
 var_dump(decimalT(10, 2)); //0b1010
 var_dump(decimalT(7, 8));    //07
 var_dump(decimalT(31, 16)); //0x1f

 


相關文章