位字段成员的大小? [英] Size of a bitfield member?

查看:197
本文介绍了位字段成员的大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人知道如何提取位字段成员的大小。下面的代码自然地给了我一个整数的大小,但是如何找出多少位或字节在 mybits.one ?我试过 sizeof(test.one)但是显然不会工作。我知道这是一个量度的位:

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;
}


推荐答案

运行时解决方案,本次讨论: http://social.msdn.microsoft.com/Forums/en-US/7e4f01b6-2e93-4acc-ac6a-b994702e7b66/finding-size-of-bitfield

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;
}

列印15。

这篇关于位字段成员的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆