十进制转化为2/8/16

<?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

 

posted @ 2016-01-18 14:55  天道酬勤,坚持!  阅读(333)  评论(0编辑  收藏  举报