Bit field vs Bitset

后端 未结 5 1928
广开言路
广开言路 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:43

    Because approach nr. 2 actually uses 100 bits of storage, plus some very minor (constant) overhead, while nr. 1 typically uses four bytes of storage per Bit structure. In general, a struct is at least one byte large per the C++ standard.

    #include 
    #include 
    
    struct Bit { int data : 1; };
    
    int main()
    {
        Bit a[100];
        std::bitset<100> b;
        std::cout << sizeof(a) << "\n";
        std::cout << sizeof(b) << "\n";
    }
    

    prints

    400
    16
    

    Apart from this, bitset wraps your bit array in a nice object representation with many useful operations.

提交回复
热议问题