-
-
- e388a4556c0f65e1904146cc1a846beevar_dump(decto_bin(array(128,253),2));
- var_dump(decto_bin(array(128,253),8));
- var_dump(decto_bin(array(128,253),16));94b3e26ee717c64999d7867364b1b4a3
- e388a4556c0f65e1904146cc1a846beeX-Powered-By: PHP/5.2.0
- Content-type: text/html94b3e26ee717c64999d7867364b1b4a3
- e388a4556c0f65e1904146cc1a846beearray(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"
- }94b3e26ee717c64999d7867364b1b4a3
-
复制代码
2,二进制、八进制、十六进制转十进制
此转换用乘法,如:1101 转十进制:1*2^3 1*2^2 0*2^1 1*2^0
代码:
<?php
/**
*二进制、八进制、十六进制 转十进制
* edit by bbs.it-home.org
*
* @param array $datalist 传入数据array(df,ef)
* @param int $bin 转换的进制可以是:2,8,16
* @return array 返回数据 array() 返回没有数据转换的格式
*/
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; //为10进制不转换
$aOutData=array(); //定义输出保存数组
foreach ($datalist as $num)
{
$atnum=str_split($num); //将字符串分割为单个字符数组
$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;
}
?>
测试:
-
-
- e388a4556c0f65e1904146cc1a846beevar_dump(bin_todec(array('ff','ff33','cc33'),16));
- var_dump(bin_todec(array('1101101','111101101'),2));
- var_dump(bin_todec(array('1234123','12341'),8));94b3e26ee717c64999d7867364b1b4a3
- e388a4556c0f65e1904146cc1a846beeX-Powered-By: PHP/5.2.0
- Content-type: text/html94b3e26ee717c64999d7867364b1b4a3
- e388a4556c0f65e1904146cc1a846beearray(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)
- }94b3e26ee717c64999d7867364b1b4a3
-
复制代码
总结:
在php中内置不少函数可以完成以上的进制转换,比如bindec(),decoct(),dechex() base_convert() decbin()等。
通过本文,带给大家一个实现php中进制转换的思路,希望对大家有所帮助。
|