前些时候工作时候,需要用到进制转换,这个问题在刚刚接触计算机理论时候,还是很会的,好久不用,居然模糊了……
1 | 从十进制向其它进制转换,用的是就用该数字不断除以要转换的进制数,读取余数。连接一起就可以了。 |
3 | *十进制转二进制、八进制、十六进制 不足位数前面补零* |
5 | * @param array $datalist 传入数据 array (100,123,130) |
6 | * @param int $bin 转换的进制可以是:2,8,16 |
7 | * @ return array 返回数据 array () 返回没有数据转换的格式 |
8 | * @Author chengmo QQ:8292669 |
03 | function decto_bin( $datalist , $bin ) |
05 | static $arr = array (0,1,2,3,4,5,6,7,8,9, 'A' , 'B' , 'C' , 'D' , 'E' , 'F' ); |
06 | if (! is_array ( $datalist )) $datalist = array ( $datalist ); |
07 | if ( $bin ==10) return $datalist ; |
08 | $bytelen = ceil (16/ $bin ); |
10 | foreach ( $datalist as $num ) |
13 | $num = intval ( $num ); |
14 | if ( $num ===0) continue ; |
17 | $t = $arr [ $num % $bin ]. $t ; |
18 | $num = floor ( $num / $bin ); |
20 | $tlen = strlen ( $t ); |
21 | if ( $tlen % $bytelen !=0) |
23 | $pad_len = $bytelen - $tlen % $bytelen ; |
24 | $t = str_pad ( "" , $pad_len , "0" ,STR_PAD_LEFT). $t ; |
测试:
var_dump(decto_bin(array(128,253),2));
var_dump(decto_bin(array(128,253),8));
var_dump(decto_bin(array(128,253),16));
X-Powered-By: PHP/5.2.0
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"
}
这个转换用乘法,如:1101 转十进制:1*2^3+1*2^2+0*2^1+1*2^0
代码:
10 | function bin_todec( $datalist , $bin ) |
12 | 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); |
13 | if (! is_array ( $datalist )) $datalist = array ( $datalist ); |
14 | if ( $bin ==10) return $datalist ; |
16 | foreach ( $datalist as $num ) |
18 | $atnum = str_split ( $num ); |
19 | $atlen = count ( $atnum ); |
22 | foreach ( $atnum as $tv ) |
24 | $tv = strtoupper ( $tv ); |
26 | if ( array_key_exists ( $tv , $arr )) |
28 | if ( $arr [ $tv ]==0) continue ; |
29 | $total = $total + $arr [ $tv ]*pow( $bin , $atlen - $i ); |
33 | $aOutData []= $total ; |
测试:
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
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)
}
后话,这些只是实现方式,其实不在乎php语言还是其它,实现思路都是一样的。php其实内置不少函数可以完成这些内容:
bindec(),decoct(),dechex() base_convert() decbin() 这里只是实现思路而已。呵呵!