Php implements binary conversion (binary, octal, and hexadecimal) to implement code conversion. For more information, see. Convert decimal to binary, octal, and hexadecimal
To convert from decimal to other hexadecimal values, the number is used to continuously divide by the number of hexadecimal values to be converted and read the remainder. Connect them together.
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; // The length of less than one byte. The value 0 is automatically added before.} $ aOutChar [] = $ t;} return $ aOutChar ;}
Test:
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"
}
Binary, octal, and hexadecimal to decimal
This conversion uses multiplication, for example: 1101 to decimal: 1*2 ^ 3 + 1*2 ^ 2 + 0*2 ^ 1 + 1*2 ^ 0
Code:
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 $ aOutData = array (); // define the output to save the array foreach ($ datalist as $ num) {$ atnum = str_split ($ num ); // split the 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 ;}
Test:
Var_dump (bin_todec (array ('FF ', 'ff33', 'cc33'), 16 ));
Var_dump (bin_todec (array ('20140901', '20160901'), 2 ));
Var_dump (bin_todec (array ('20140901', '20160901'), 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)
}
Later, these are just implementation methods. In fact, they do not care about php or other languages, and the implementation ideas are the same. Php actually has many built-in functions to accomplish this:
Bindec (), decoct (), dechex () base_convert () decbin () is just the implementation idea here.
For more php code conversion (binary, octal, and hexadecimal), please follow the PHP Chinese website!