There is a requirement in the project, that is, decimal into binary, octal, hexadecimal, and binary, octal, hexadecimal to decimal, the following record, later use can be easily picked.
From decimal to other binary conversions, the remainder is read by dividing the number by the number of binary numbers to be converted. Connected together on it. Here is the decimal conversion to binary, octal, 16 binary:
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 one byte length, automatically preceded by 0 } $aOutChar []= $t; }
The test results are as follows:
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.0content-type:text/htmlarray (2) { [0]=> string (8) "10000000" [1]=> String (8) "11111101"}array (2) { [0]=> string (4) "0200" [1]=> string (4) "0375"}array (2) { [0]=> String (2) "[1]=>" string (2) "FD"}
Binary, octal, hexadecimal to decimal with multiplication, such as: 1101 to decimal: 1*2^3+1*2^2+0*2^1+1*2^0, program design as follows:
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; For 10 binary does not convert $aOutData =array ();//define Output Save array foreach ($datalist as $num) { $atnum =str_split ($num); Splits a string into a single character array $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;}
The test is as follows:
Var_dump (Bin_todec (Array (' FF ', ' ff33 ', ' cc33 ')), Var_dump (Bin_todec (' 1101101 ', ' 111101101 '), 2); var_dump (Bin_todec (Array (' 1234123 ', ' 12341 '), 8)); X-powered-by:php/5.2.0content-type:text/htmlarray (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)}
These are just ways to implement, in fact, do not care PHP language or other, the realization of ideas are the same. PHP actually has a few built-in functions to do this: Bindec (), Decoct (), Dechex () Base_convert () Decbin () Here is just the idea.
http://www.bkjia.com/PHPjc/752455.html www.bkjia.com true http://www.bkjia.com/PHPjc/752455.html techarticle there is a requirement in the project that decimal is converted to binary, octal, hex, binary, octal, hexadecimal to decimal, recorded below, later used ...