bit vector implementation of set in Programming Pearls, 2nd Edition

前端 未结 3 842
执念已碎
执念已碎 2021-01-30 04:39

On Page 140 of Programming Pearls, 2nd Edition, Jon proposed an implementation of sets with bit vectors.

We\'ll turn now to two final structures that exploit the fact

3条回答
  •  情书的邮戳
    2021-01-30 05:26

    If you store your bits in an array of n words you can imagine them to be layed out as a matrix with n rows and 32 columns (BITSPERWORD):

             3                                         0
             1                                         0
          0  xxxxxxxxxx xxxxxxxxxx xxxxxxxxxx xxxxxxxxxx
          1  xxxxxxxxxx xxxxxxxxxx xxxxxxxxxx xxxxxxxxxx
          2  xxxxxxxxxx xxxxxxxxxx xxxxxxxxxx xxxxxxxxxx     
          ....
          n  xxxxxxxxxx xxxxxxxxxx xxxxxxxxxx xxxxxxxxxx
    

    To get the k-th bit you divide k by 32. The (integer) result will give you the row (word) the bit is in, the reminder will give you which bit is within the word.

    Dividing by 2^p can be done simply by shifting p postions to the right. The reminder can be obtained by getting the p rightmost bits (i.e the bitwise AND with (2^p - 1)).

    In C terms:

    #define div32(k) ((k) >> 5)
    #define mod32(k) ((k) & 31)
    
    #define word_the_bit_is_in(k) div32(k)
    #define bit_within_word(k)    mod32(k)
    

    Hope it helps.

提交回复
热议问题