Size of a bitfield member?

bit, bit-fields, c++

Solution

Runtime solution, the idea from this discussion: http://social.msdn.microsoft.com/Forums/en-US/7e4f01b6-2e93-4acc-ac6a-b994702e7b66/finding-size-of-bitfield

#include <iostream>
using namespace std;

int BitCount(unsigned int value)
{
    int result = 0;

    while(value)
    {
        value &= (value - 1);
        ++result;
    }

    return result;
}

int main()
{
    struct mybits {
        unsigned int one:15;
    };

    mybits test;
    test.one = ~0;

    cout << BitCount(test.one) << endl;

    return 0;
}

Prints 15.

Problem

Would anyone know how to extract the size of a bit-field member. The below code naturally gives me the size of an integer, but how do I find out how many bits or bytes are in `mybits.one`? I've tried `sizeof(test.one)` but which clearly won't work. I realize this is a measure of bits: ``` #include <iostream> using namespace std; int main() { struct mybits { unsigned int one:15; }; mybits test; test.one = 455; cout << test.one << endl; cout << "The size of test.one is: " << sizeof(test) << endl; } ```

Original source