利用php数组实现Bitset位处理模块功能

接上篇,php的bitset模块介绍和安装

利用php的bitset模块可以实现c++的bitset相关功能。但是,在生产环境下需要给线上服务器安装模块是很危险和麻烦的事,所以需要另辟蹊径。

我用php的array数组模拟了bitset的几个主要方法的实现过程,其实就是利用Array的key模拟内存地址,value模地址内容。php的Array还是超级方便的 :)

 1 <?php
 2 define('CHAR_BIT', 8);
 3 /**
 4  * bitset操作php实现
 5  * @version:1.0
 6  * @author:Kenny{Kenny.F<mailto:kennyffly@gmail.com>}
 7  * @since:2014/05/21
 8  */
 9 class Bitset {
10 
11     private $bitset_data = array();
12     private $_len = 0;
13 
14     //分配位数组空间
15     function &bitset_empty($bit=0)
16     {
17         if(!is_numeric($bit) || $bit<0)
18         {
19             echo "argument must be a positive integer";
20             return False;
21         }
22         $this->_len = $bit;
23         return $this->bitset_data;
24     }
25 
26     //位数组位置$bit上的值置为1
27     public function bitset_incl(&$bitset_data=array(), $bit=0)
28     {
29         if (!is_numeric($bit) || $bit<0)
30         {
31             echo "Second argument must be a positive integer";
32             return False;
33         }
34 
35         $bitset_temp = isset($bitset_data[intval($bit/CHAR_BIT)]) ? $bitset_data[intval($bit/CHAR_BIT)] : 0;
36         $bitset_data[intval($bit/CHAR_BIT)]  = $bitset_temp | 1 << ($bit % CHAR_BIT);
37 
38         unset($bitset_data);
39     }
40 
41     //判断某个位置bit上的值是否为1
42     public function bitset_in($bitset_data=array(), $bit=0)
43     {
44         if (!is_array($bitset_data))
45         {
46             echo "first argument is not a array";
47             return False;
48         }
49 
50         if ($bit < 0)
51         {
52             return False;
53         }
54         if ($this->_len == 0)
55         {
56             return False;
57         } elseif($bit >= $this->_len*CHAR_BIT){
58             return False;
59         } elseif ($bitset_data[intval($bit/CHAR_BIT)] & (1 << ($bit % CHAR_BIT))){
60             return True;
61         } else{
62             return False;
63         }
64     }
65 
66 }

你可以查看我的github

posted on 2014-09-10 11:23  齐柏林飞艇  阅读(738)  评论(0编辑  收藏  举报