第27条 数据格式和效率之二:(甚至更少的)位操纵
class CBitBuffer
{
public:
CBitBuffer(){};
virtual ~CBitBuffer(){};
size_t Size() const{
return buf_.size();
}
void Append(unsigned char* p ,size_t num)
{
int bits = numeric_limits<unsigned char>::digits;
for(int i= 0; i<num;++i)
{
buf_.push_back((*p)&(1<<(bits-1-i%bits)));
if ((i+1)%bits == 0)
++p;
}
}
void Get(size_t start,size_t num,unsigned char *dst)const
{
int bits = numeric_limits<unsigned char>::digits;
*dst = 0;
for(int i= 0;i<num;++ i)
{
*dst |= unsigned char(buf_[start + i]<<(bits -1 -i%bits));
if ((i+1)%bits == 0)
* ++ dst = 0;
}
}
private:
vector<bool> buf_;
};
Herb Sutter的位容器,看上去很不错,我也很喜欢。附上代码,以后用的机会可能也不会很多吧。