Iterate bit field members

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 elements automatically, something like this:
ce {0-10}?
Let's say I want to read c.e0 and then c.e1 ...
If my structure had 1000 elements, I don’t think 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 to this problem, but I did not find a solution.

Many thanks!

+3
source share
5 answers

, , , . , 6- . , . 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;
}

companion put() .

+4

, , . array, vector, . - , .

(, ), .

struct X {
   int[10] numbs;
   string name;
};

X c;
+3

. , C, ++.

+2

- :

char getByte(char *startPos, int index) {

    int i = (index*6) / 8;

    if (index % 4 == 0)
        return 0b11111100 & startPos[i] >> 2;
    else if (index % 4 == 3)
        return 0b00111111 & startPos[i];
    else if (index % 4 == 2)
        return (0b00001111 & startPos[i] << 2) | (0b11000000 & startPos[i+1] >> 6);
    else
        return (0b00000011 & startPos[i] << 4) | (0b11110000 & startPos[i+1] >> 4);
}
+2

Since your bit fields are the same size, you can encapsulate std::bitset(or vector<bool>, gulp ...) and provide your own iterators (each step moving the bookmark six bits) and operator[](etc.) to make your code easier to write.

I'm sure performance will suck compared to bitfields.

+2
source

Source: https://habr.com/ru/post/1773685/


All Articles