0

I am just confused about exact size of a bitset<32> element.

As the document for std::bitset::size says:

Returns the number of bits in the bitset.

As the document of sizeof says

Returns size in bytes of the object representation of type.

So I tried to use the two functions in the following program

#include <iostream>

using namespace std;

int main(){
    unsigned char a = 0; // a = 5(00000101)
    std::bitset<32> x(a);

    cout << sizeof(x) << endl;
    cout << x.size() << endl;
    return 0;
}

The output is

8 
32

Why doesn't the sizeof(x) return 4? As 32 bits should be equal to 4 bytes, instead of 8?

yuqli
  • 4,461
  • 8
  • 26
  • 46
  • 3
    `sizeof()` gives you the space actually needed in memory. On a 64 bit machine architecture it would be quite likely that a `std::bitset<32>` is stored using an underlying `uint64_t` instead of a `uint32_t`. – πάντα ῥεῖ Jul 22 '18 at 19:10
  • got it. thanks! I also find this link with similar ideas helpful : https://stackoverflow.com/questions/12459563/what-is-the-size-of-bitset-in-c – yuqli Jul 22 '18 at 19:13

0 Answers0