Home  >  Article  >  Backend Development  >  Convert decimal to binary, octal, hexadecimal and add zeros in front of the missing digits_PHP Tutorial

Convert decimal to binary, octal, hexadecimal and add zeros in front of the missing digits_PHP Tutorial

WBOY
WBOYOriginal
2016-07-20 11:09:025247browse

/**
*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;
}

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/444835.htmlTechArticle?php tutorial/** *Add zeros in front of the missing digits from decimal to binary, octal and hexadecimal* * * @param array $datalist Incoming data array(100,123,130) * @param int $bin The converted base...
Statement:
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