PHP to achieve the conversion of binary octal hexadecimal) mutual conversion code

  • 2020-03-31 21:21:28
  • OfStack

Convert decimal to binary, octal, and hexadecimal
To convert from decimal to other bases, you simply divide the number by the base number to be converted and read the remainder. Just connect them together.
 
<?php 
 
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 ignore
$bytelen=ceil(16/$bin); //Get the length of one byte if it's in $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; //Less than a byte in length, automatically preceded by 0
} 
$aOutChar[]=$t; 
} 
return $aOutChar; 
} 

Testing:
Var_dump (decto_bin (array (128253), 2));
Var_dump (decto_bin (array (128253), 8));
Var_dump (decto_bin (array (128253), 16));

X - Powered By: PHP / 5.2.0
The content-type: text/HTML
Array (2) {
[0] = >
String (8) "10000000"
[1] = >
String (8) "11111101"
}
Array (2) {
[0] = >
String (4) "0200"
[1] = >
String (4) "0375"
}
Array (2) {
[0] = >
String (2) "80"
[1] = >
String (2) "FD"
}
Binary, octal, hexadecimal to decimal
This conversion USES multiplication, such as 1101 to decimal: 1*2^3+1*2^2+0*2^1+1*2^0
Code:

 
<?php 
 
function bin_todec($datalist,$bin) 
{ 
static $arr=array('0'=>0,'1'=>1,'2'=>2,'3'=>3,'4'=>4,'5'=>5,'6'=>6,'7'=>7,'8'=>8,'9'=>9,'A'=>10,'B'=>11,'C'=>12,'D'=>13,'E'=>14,'F'=>15); 
if(!is_array($datalist))$datalist=array($datalist); 
if($bin==10)return $datalist; //Do not convert for base 10
$aOutData=array(); //Define the output save array
foreach ($datalist as $num) 
{ 
$atnum=str_split($num); //Splits a string into an array of individual characters
$atlen=count($atnum); 
$total=0; 
$i=1; 
foreach ($atnum as $tv) 
{ 
$tv=strtoupper($tv); 
if(array_key_exists($tv,$arr)) 
{ 
if($arr[$tv]==0)continue; 
$total=$total+$arr[$tv]*pow($bin,$atlen-$i); 
} 
$i++; 
} 
$aOutData[]=$total; 
} 
return $aOutData; 
} 

Testing:
Var_dump (bin_todec (array (' ff ', 'ff33', 'cc33), 16));
Var_dump (bin_todec (array (' 1101101 ', '111101101'), 2));
Var_dump (bin_todec (array (' 1234123 ', '12341'), 8));

X - Powered By: PHP / 5.2.0
The content-type: text/HTML
Array (3) {
[0] = >
Int (255).
[1] = >
Int (65331).
[2] = >
Int (52275).
}
Array (2) {
[0] = >
Int (124).
[1] = >
Int (508).
}
Array (2) {
[0] = >
Int (342099).
[1] = >
Int (5345).
}
Later, these are just the way to implement, actually don't care about PHP language or other, the implementation ideas are the same. There are a number of built-in PHP functions that do this:
Bindec (), decoct(), dechex() base_convert() decbin() are just implementation ideas here. Ha ha!

Related articles: