迭代位域的成员

bsd*_*bsd 4 c++ bit-fields

我们有这样的例子:

struct X {
  int e0 : 6;
  int e1 : 6;
  int e2 : 6;
  ...
  int e10 : 6;
};

struct X c;
Run Code Online (Sandbox Code Playgroud)

如何“自动”访问成员,例如:
ce{0-10}?
假设我想读取 c.e0,然后 c.e1 ...
如果我的结构有 1000 个元素,我认为我不应该编写这么多代码,对吗?

你能帮我想一个解决方法、一个想法吗?
我提到我已经阅读了与此问题相关的其他帖子,但我没有找到解决方案。

非常感谢 !

Bil*_*ter 5

正如其他人所说,您无法使用位字段完全执行您想要的操作。看起来您想以最大的空间效率存储大量 6 位整数。我不会争论这是否是一个好主意。相反,我将提出一种类似老式 C 的方法来实现这一点,即使用 C++ 功能进行封装(未经测试)。这个想法是 4 个 6 位整数需要 24 位,即 3 个字符。

// In each group of 3 chars store 4 6 bit ints
const int nbr_elements = 1000;
struct X
{
    // 1,2,3 or 4 elements require 3 chars, 5,6,7,8 require 6 chars etc.
    char[ 3*((nbr_elements-1)/4) + 3 ] storage;
    int get( int idx );
};

int X::get( int idx )
{
    int dat;
    int offset = 3*(idx/4);      // eg idx=0,1,2,3 -> 0 idx=4,5,6,7 -> 3 etc.
    char a = storage[offset++];
    char b = storage[offset++];
    char c = storage[offset];
    switch( idx%4)  // bits lie like this; 00000011:11112222:22333333
    {
        case 0: dat = (a>>2)&0x3f;                    break;
        case 1: dat = ((a<<4)&0x30) + ((b>>4)&0x0f);  break;
        case 2: dat = ((b<<2)&0x3c) + ((c>>6)&0x03);  break;
        case 3: dat = c&0x3f;                         break;
    }   
    return dat;
}
Run Code Online (Sandbox Code Playgroud)

我将把配套的 put() 函数作为练习。