【问题标题】:C++ 2-bit bitfield arrays possible?C++ 2位位域数组可能吗?
【发布时间】:2014-08-19 11:15:11
【问题描述】:

我有一个这样的 2 位位域结构:

struct MyStruct {
    unsigned __int32 info0  : 2;
    unsigned __int32 info1  : 2;
    unsigned __int32 info2  : 2;
   ...
    unsigned __int32 info59 : 2;
};

还有一个像这样的高达 120... 有没有办法将它们写入和寻址为数组?

【问题讨论】:

  • 也许你可以在std::bitset<240> 周围加上一些东西?
  • 通过形成指向每个元素的指针来访问常规数组,并且您不能拥有指向位域的指针。

标签: c++ bit-fields


【解决方案1】:

如果您出于某种原因不能使用 Paul R 的答案,您始终可以使用带有标准数组的自定义访问器:

static unsigned __int8 infos[30]; // 240 bits allocated

unsigned __int8 getInfo( unsigned short id_num )
{
    return (infos[id_num/4] >> ((2*id_num) % 8) ) & 0x3;
}
// setInfo left as an exercise.

(这里可能需要检查逻辑,我没有测试过。)

【讨论】:

  • 你应该用sizeof替换4,否则很好回答!
  • @Quentin :好吧,OP 使用的是 __intxx,它们是位长定义的类型,因此 sizeof 在这里并不是很有用。否则我同意。
  • 我错了,还是这段代码返回了对临时的引用?
  • 另外,我认为移位应该乘以位域元素宽度2。否则你永远不会访问数组元素的上半部分。
  • @user2079303:它有很大的缺陷。 8 * 40 也不是 240。
【解决方案2】:

我将使用代理对象来创建一个临时引用,该引用可用于使用数组语法操作 2 位项目。这可以很容易地修改为处理 n 位项目。

#include <iostream>

class TwoBitArray {
public:
    typedef unsigned char byte;

    TwoBitArray(unsigned size) : bits(new byte[(size + 3) / 4]) {}
    ~TwoBitArray() { delete bits; }

    class tbproxy {
    public:
        tbproxy(byte& b, int pos) : b(b), pos(pos) {}

        // getter
        operator int() const {
            return (b >> (pos * 2)) & 3;
        }

        // setter
        tbproxy operator=(int value) {
            const byte mask = ~(3 << (pos * 2));
            b = (b & mask) | (value << (pos * 2));
            return *this;
        }

    private:
        byte& b;
        int pos;
    };

    // create proxy to manipulate object at index
    tbproxy operator[](int index) const {
        return tbproxy(bits[index/4], index & 3);
    }

private:
    byte* bits;
};

int main() {
    const int size = 20;
    TwoBitArray a(size);
    for (int i = 0; i < size; ++i)
        a[i] = i & 3;
    for (int i = 0; i < size; ++i)
        std::cout << i << ": " << a[i] << std::endl;
}

【讨论】:

  • 我喜欢这个答案,当然感谢您花时间写它!就我而言,这有点矫枉过正,所以我会选择另一个答案。但是,了解为什么您会选择使用代理类而不是简单的访问器方法会很有趣?
  • @Robin - 如果一个对象在逻辑上形成一个数组,我更愿意使用数组语法访问它。对我来说,为类的用户提供一个干净、简单和明显的接口远远超过任何实现复杂性问题。即使(尤其是如果:)那个用户是我。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-12-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多