Size of a bitfield member?

后端 未结 6 1074
傲寒
傲寒 2020-12-29 07:42

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 b

6条回答
  •  春和景丽
    2020-12-29 08:00

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

提交回复
热议问题