bitset实现

  最近看到C++的bitset,突然好奇他们是怎么实现的。对内存的管理不可避免要用到指针,可是指针是用类型的,对bit的管理用什么指针效率高呢?于是就自己尝试写了个用char*来管理内存的bitset,当然自己这个效率稳健都无法于源码相比,所以命名成BitMap,只当是练习了。不过经过我的测试,发现这种方法的效率并不比c++的bitset效率低。  

  主要代码如下(Download):

#include <iostream>
#include <malloc.h>
using namespace std;

/*
*This class implemented BitMap with the memory management using char* type
*it provide three public functions:
*
*getBit(unsigned long index) get the bit value in position index
*
*setBit(unsigned long index, bool value) set the bit value in position index
*
*printBitMap() print the bits
*
*/
class BitMap{
public:
bool getBit(unsigned long index);
void setBit(unsigned long index,bool value);
void printBitMap();

/*
* the construction and destruction
*/
public:
typedef unsigned char u_char;
BitMap(unsigned long length);
~BitMap();

private:
unsigned long buf_size;
u_char *buf;
inline u_char _set1(u_char data,int number){
return data|0x1<<number;
}
inline u_char _set0(u_char data,int number){
return data&~(0x1<<number);
}
inline bool _getbit(u_char data,int number){
return (data>>number)&0x1;
}
inline void _printChar(u_char data){
char buf[9];
int i=7;
while(i>=0){
buf[i--]=(data%2==0 ? '0' : '1');
data/=2;
}
buf[8]=0;
printf("%s",buf);
}
};

BitMap::BitMap(unsigned long length){
int tmp=0;
if((tmp=length%8)!=0)
buf_size=length+8-tmp;
else
buf_size=length;
buf=(u_char*)malloc(sizeof(sizeof(char)*(buf_size/8)));
};

BitMap::~BitMap(){
free(this->buf);
};

void BitMap::setBit(unsigned long index,bool isHit){
if(index>buf_size)
return ;
int sub_index=7-index%8;
u_char *location=buf+index/8;
if(isHit)
*location=_set1(*location,sub_index);
else
*location=_set0(*location,sub_index);
};

bool BitMap::getBit(unsigned long index){
return _getbit(*(buf+index/8),7-index%8);
}

void BitMap::printBitMap(){
u_char *start=buf;
while(start<=buf+buf_size/8){
_printChar(*start);
start++;
}
printf("\n");

}

int main(int argc, char **argv){
BitMap bi(32);
cout<<"initailize the bitmap"<<endl;
bi.printBitMap();

cout<<"set the first bit to 1"<<endl;
bi.setBit(1,true);
bi.printBitMap();

cout<<"set the twenty bit to 1"<<endl;
bi.setBit(20,true);
bi.printBitMap();

bool tp=bi.getBit(20);
cout<<"is the twenty bit 1? "<< tp<<endl;

}

  网上搜索到bitset.h的源码,不过一下子被作者神乎其技的coding功夫吓呆了,没看懂。http://gcc.gnu.org/onlinedocs/libstdc++/libstdc++-html-USERS-4.2/bitset-source.html

  

posted @ 2011-12-07 16:48  渔牧  阅读(1069)  评论(0编辑  收藏  举报