位域成员的大小?

dom*_*ica 16 c++ bits bit-fields

有谁知道如何提取位字段成员的大小.下面的代码自然给出了一个整数的大小,但是如何找出有多少位或字节mybits.one?我已经尝试过,sizeof(test.one)但显然无法正常工作.我意识到这是一个衡量标准:

#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;
}
Run Code Online (Sandbox Code Playgroud)

Sha*_*our 6

草案C ++标准的sizeof不应被施加到一个位字段中部分5.3.3 的sizeof段落1。如果您可以控制源,那么使用枚举听起来更简单和整洁:

struct mybits
{
    enum bitFieldSizes
    {
        field1 = 15,
        field2 = 2,
        field3 = 4,
        field4 = 8,
        field5 = 31
    };

    unsigned int one : field1 ;  
    unsigned int two : field2 ;  
    unsigned int three : field3 ;
    unsigned int four : field4 ;
    unsigned int five : field5 ;
};
Run Code Online (Sandbox Code Playgroud)

如果您无法控制源代码,则可以使用 bit hacks 来获取位域的大小,而std::bitset则可以更轻松:

#include <iostream>
#include <bitset>

struct mybits
{
    unsigned int one : 15 ;  
    unsigned int two : 2 ;  
    unsigned int three : 4 ;
    unsigned int four : 8 ;
    unsigned int five : 31 ;
};

int main()
{
    mybits mb1 ;

    mb1.one   =  ~0 ;
    mb1.two   =  ~0 ;
    mb1.three =  ~0 ;
    mb1.four  =  ~0 ;
    mb1.five  =  ~0 ;

    std::bitset<sizeof(unsigned int)*8> b1(mb1.one);
    std::bitset<sizeof(unsigned int)*8> b2(mb1.two);
    std::bitset<sizeof(unsigned int)*8> b3(mb1.three);
    std::bitset<sizeof(unsigned int)*8> b4(mb1.four);
    std::bitset<sizeof(unsigned int)*8> b5(mb1.five);

    std::cout << b1 << ":" << b1.count() << std::endl ;
    std::cout << b2 << ":" << b2.count() << std::endl ;
    std::cout << b3 << ":" << b3.count() << std::endl ;
    std::cout << b4 << ":" << b4.count() << std::endl ;
    std::cout << b5 << ":" << b5.count() << std::endl ;
}
Run Code Online (Sandbox Code Playgroud)

产生以下输出:

00000000000000000111111111111111:15
00000000000000000000000000000011:2
00000000000000000000000000001111:4
00000000000000000000000011111111:8
01111111111111111111111111111111:31
Run Code Online (Sandbox Code Playgroud)


Ale*_*x F 5

运行时解决方案,这个讨论的想法: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;
}
Run Code Online (Sandbox Code Playgroud)

打印15.

  • 不确定,但这可能取决于编译器,因为未定义填充位的设置方式。它们可能包含垃圾。因此,请注意您如何使用它。此外,它是在运行时完成的。 (2认同)