Home >Backend Development >PHP Tutorial >Convert decimal to binary, octal, hexadecimal and add zeros in front of the missing digits_PHP Tutorial
/**
*Add zeros in front of the missing digits when converting from decimal to binary, octal or hexadecimal*
*
* @param array $datalist Pass in data array(100,123,130)
* @param int $bin The converted base can be: 2, 8, 16
* @return array Return data array() Return the format without data conversion
* @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; //Same base is ignored
$bytelen=ceil(16/$bin) ; //Get the length of one byte if it is $bin base
$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; //Insufficient One byte length, automatically prepended with 0
}
$aoutchar[]=$t;
}
return $aoutchar;
}