Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate members of a bitfield

Tags:

c++

bit-fields

We have this example:

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

struct X c;

How can I access the members "automatically", something like that:
c.e{0-10} ?
Say if I want to read c.e0, then c.e1 ...
If my struct would have 1000 elements, I do not think that I should write so much code, right ?

Can you help me with a workaround, an idea ?
I mention that I already read other posts related somehow to this problem, but I did not find a solution.

Thank you very much !

like image 258
bsd Avatar asked Dec 10 '22 12:12

bsd


1 Answers

As others have said, you cannot do exactly what you want with bit fields. It looks like you want to store a large number of 6 bit integers with maximum space efficiency. I will not argue whether this is a good idea or not. Instead I will present an old-school C like way of doing exactly that, using C++ features for encapsulation (untested). The idea is that 4 6 bit integers require 24 bits, or 3 characters.

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

I will leave the companion put() function as an exercise.

like image 91
Bill Forster Avatar answered Dec 23 '22 06:12

Bill Forster