Bit field vs Bitset

CLOWN picture CLOWN · Oct 22, 2010 · Viewed 14.6k times · Source

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 data : 1
};

int main()
{
   BIT a[100];
   return 0;
}

Approach number 2 (AN 2)

int main()
{
    std::bitset<100> BITS;
    return 0;
}

Why would someone prefer AN 2 over AN 1?

Answer

Fred Foo picture Fred Foo · Oct 22, 2010

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 <bitset>
#include <iostream>

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.