Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the size of bitset in C++

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++?

like image 345
Saurabh Avatar asked Sep 17 '12 12:09

Saurabh


People also ask

What is the size of Bitset?

The size() method of Java BitSet class returns the total number of bit space actually in use by this BitSet to represent bit values. The maximum element in the set is the size - 1st element. The default size of the bit set is 64-bit space.

What is Bitset in C?

Bitset represents a fixed-size sequence of N bits and stores values either 0 or 1. Zero means value is false or bit is unset and one means value is true or bit is set. Bitset class emulates space efficient array of boolean values, where each element occupies only one bit.

How much memory does Bitset use?

Memory Footprint As shown above, this boolean[] consumes around 10 KB of memory. As expected, the BitSet with the same number of bits consumes around 1 KB, which is far less than the boolean[].


2 Answers

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

like image 181
PiotrNycz Avatar answered Sep 18 '22 15:09

PiotrNycz


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

There is no information in standard about how bitset should be realized. It's implementation defined, look at bitset header of your compiler.

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

No, there is no method to allocate space in bits in C++.

like image 45
ForEveR Avatar answered Sep 19 '22 15:09

ForEveR