Bit field vs Bitset

后端 未结 5 1930
广开言路
广开言路 2021-02-05 08:17

I want to store bits in an array (like structure). So I can follow either of the following two approaches

Approach number 1 (AN 1)

struct BIT
{
   int da         


        
5条回答
  •  迷失自我
    2021-02-05 08:24

    To quote cplusplus.com's page on bitset, "The class is very similar to a regular array, but optimizing for space allocation". If your ints are 4 bytes, a bitset uses 32 times less space.

    Even doing bool bits[100], as sbi suggested, is still worse than bitset, because most implementations have >= 1-byte bools.

    If, for reasons of intellectual curiosity only, you wanted to implement your own bitset, you could do so using bit masks:

    typedef struct {
      unsigned char bytes[100];
    } MyBitset;
    
    bool getBit(MyBitset *bitset, int index)
    {
      int whichByte = index / 8; 
      return bitset->bytes[whichByte] && (1 << (index = % 8));
    }
    
    bool setBit(MyBitset *bitset, int index, bool newVal)
    {
      int whichByte = index / 8;
    
      if (newVal)
      {
        bitset->bytes[whichByte] |= (1 << (index = % 8));
      }
      else
      {
        bitset->bytes[whichByte] &= ~(1 << (index = % 8));
      }
    }
    

    (Sorry for using a struct instead of a class by the way. I'm thinking in straight C because I'm in the middle of a low-level assignment for school. Obviously two huge benefits of using a class are operator overloading and the ability to have a variable-sized array.)

提交回复
热议问题