STL源码分析之bitset源码分析 原

做为一名程序员,写技术型博客还是很有必要的,那就从这里开始吧。


看了两天的bitset源码,觉得理解下面几点后,看源码应该不难了。


bitset存储二进制数,是以arr[ulong] 这样的一个数组方式存储的。

每一个ulong存储32位的bit。


所以当你声明一个bitset<n>时,就得计算需要多少个ulong来存储这些bit

__BITSET_WORDS就是这样作用的。

#define __BITSET_WORDS(__n) \
 ((__n) < 1 ? 1 : ((__n) + __BITS_PER_WORD - 1)/__BITS_PER_WORD)


__BITS_PER_WORD:计算每个ulong占用多少位Bit。

#define __BITS_PER_WORD (CHAR_BIT*sizeof(unsigned long))


_S_bit_count:这个静态数组,保存着256个char,每个char有多少位1

如7 = 0111,即_S_bit_count[7] = 3

template<bool __dummy> 
struct _Bit_count {
  static unsigned char _S_bit_count[256];
};


_S_first_one:这个静态数组,保存着每个char里,第一个bit 1,后面有多少位0

如:6 = 0110 _S_first_one[6] = 1;

如:8 = 1000 _S_first_one[8] = 3;

template<bool __dummy> 
struct _First_one {
  static unsigned char _S_first_one[256];
};


_S_whichword: 获取二进制位__pos,在数组_M_w中下标是几。

_S_whichbyte: 获取在word中,第几个char。

_S_whichbit: 获取在word中,第几个bit。


(重要,也比较难理解)_S_maskbit:

取__pos位,在当前ulong中的掩码。

如: _S_whichword(__pos) = 5,_S_whichbit(__pos) = 3

    即:_S_maskbit(__pos) = 00...00 0100

    数组5下的word,第3个值的掩码1,

    为接口set,reset,flip等使用

  static _WordT _S_maskbit( size_t __pos )
    { return (static_cast<_WordT>(1)) << _S_whichbit(__pos); }



_M_do_sanitize:使__val高_Extrabits位,置0。

template <size_t _Extrabits> struct _Sanitize {
  static void _M_do_sanitize(unsigned long& __val)
    // (~static_cast<unsigned long>(0)) : 1111 1111...
    // (~static_cast<unsigned long>(0)) << _Extrabits : 1111...000
    // ~((~static_cast<unsigned long>(0)) << _Extrabits): 000...111
    { __val &= ~((~static_cast<unsigned long>(0)) << _Extrabits); }
};



带有详细注释的bitset源码文件

下载地址:http://pan.baidu.com/s/1hqePcB6

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章