What is the size of bitset in C++

Saurabh picture Saurabh · Sep 17, 2012 · Viewed 12.7k times · Source

I want to know how bitset actually allocates memory. I read from some blog that it takes up memory in bits. However when i run the following code:

   bitset<3> bits = 001;
   cout<<sizeof(bits);

I get the output as 4. What is the explanation behind it?

Also is there a method to allocate space in bits in C++?

Answer

PiotrNycz picture PiotrNycz · Sep 17, 2012

You can approximate sizeof(bitset<N>) as:

  1. If internal representation is 32bit (like unsigned on 32bit systems) as 4 * ((N + 31) / 32)
  2. If internal representation is 64bit (like unsigned long on 64bit systems) as 8 * ((N + 63) / 64)

It seems that the first is true: 4 * ((3 + 31) / 32) is 4