Saurabh
Saurabh

Reputation: 353

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

Upvotes: 18

Views: 23424

Answers (5)

ForEveR
ForEveR

Reputation: 55887

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 the <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++.

Upvotes: 10

PiotrNycz
PiotrNycz

Reputation: 24402

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

Upvotes: 16

jrtc27
jrtc27

Reputation: 8526

Typically on a 32-bit processor, the compiler will make the allocated memory size a multiple of 4 bytes, and so the nearest multiple of 4 greater than 3/8 is 4 bytes.

Upvotes: 1

Juho
Juho

Reputation: 953

Your CPU doesn't operate with individual bits, but with bytes and words. In your case, sizeof(bits) results in 4 because compiler decided to align this datastructure to 4 bytes.

Upvotes: 8

nothrow
nothrow

Reputation: 16168

You cannot address separate bits, the lowest adressable unit is byte. So no, you cannot allocate bits precisely.

Another thing is padding - you almost always get more bytes allocated that you asked for, this is for optimalization purposes. Addressing bytes not on 32b boundaries is often expensive, addressing bytes on x64 CPU that are not on 64b boundaries results in exception. (speaking of Intel platform.)

Upvotes: 0

Related Questions