1 <?php
 2     #二进制相加
 3     function binary_plus($binstr1, $binstr2) {
 4         $bin_arr1 = str_split($binstr1);
 5         $bin_arr2 = str_split($binstr2);
 6         $arr_len1 = count($bin_arr1);
 7         $arr_len2 = count($bin_arr2);
 8         $sum_arr = array();
 9 
10         if ($arr_len1 < $arr_len2) {
11             $short_arr = &$bin_arr1;
12         } else {
13             $short_arr = &$bin_arr2;
14         }
15 
16         #将两个数组的长度补到一样长,短数组在前面补0
17         for ($i = 0; $i < abs($arr_len1 - $arr_len2); $i++) {
18             array_unshift($short_arr, 0);
19         }
20 
21         $carry = 0;    #进位标记
22         for ($i = count($bin_arr1) - 1; $i >= 0; $i--) { 
23             $result = $bin_arr1[$i] + $bin_arr2[$i] + $carry;
24             switch ($result) {
25                 case 0:
26                     array_unshift($sum_arr, 0);
27                     $carry = 0;
28                     break;
29                 case 1:
30                     array_unshift($sum_arr, 1);
31                     $carry = 0;
32                     break;
33                 case 2:
34                     array_unshift($sum_arr, 0);
35                     $carry = 1;
36                     break;
37                 case 3:
38                     array_unshift($sum_arr, 1);
39                     $carry = 1;
40                     break;
41                 default:
42                     die();
43             }
44         }
45 
46         if($carry == 1) {
47             array_unshift($sum_arr, 1);
48         }
49 
50         return implode("", $sum_arr);
51     }
52 
53     $bin1 = "1001101";
54     $bin2 = "1010";
55     print_r(binary_plus($bin1, $bin2));
56 ?>
posted on 2012-09-12 04:48  ZimZz  阅读(1621)  评论(0编辑  收藏  举报