Home > php教程 > php手册 > 十进制转二进制、八进制、十六进制 不足位数前面补零

十进制转二进制、八进制、十六进制 不足位数前面补零

WBOY
Release: 2016-06-13 11:24:54
Original
2035 people have browsed it

 

/**
*十进制转二进制、八进制、十六进制 不足位数前面补零*
*
* @param array $datalist 传入数据array(100,123,130)
* @param int $bin 转换的进制可以是:2,8,16
* @return array 返回数据 array() 返回没有数据转换的格式
* @copyright chengmo qq:8292669
*/
function decto_bin($datalist,$bin)
{
static $arr=array(0,1,2,3,4,5,6,7,8,9,'a','b','c','d','e','f');
if(!is_array($datalist)) $datalist=array($datalist);
if($bin==10)return $datalist; //相同进制忽略
$bytelen=ceil(16/$bin); //获得如果是$bin进制,一个字节的长度
$aoutchar=array();
foreach ($datalist as $num)
{
$t="";
$num=intval($num);
if($num===0)continue;
while($num>0)
{
$t=$arr[$num%$bin].$t;
$num=floor($num/$bin);
}
$tlen=strlen($t);
if($tlen%$bytelen!=0)
{
$pad_len=$bytelen-$tlen%$bytelen;
$t=str_pad("",$pad_len,"0",str_pad_left).$t; //不足一个字节长度,自动前面补充0
}
$aoutchar[]=$t;
}
return $aoutchar;
}

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template