Search code examples
cstructbit-fields

How can I access an element of a bit-field structure in C at runtime?


I have a structure coloring with bit fields defined in C, and one such structure called color

struct coloring {
    unsigned int a : 3;
    unsigned int b : 3;
    unsigned int c : 3;
    unsigned int d : 3;
    unsigned int e : 3;
    unsigned int f : 3;
   ...
    unsigned int v : 3;
};
void main(){
struct coloring color;
}

I want to access and possibly edit a certain element, depending on rules extraneous to this specific question. During the running time, I figure out which element I want to ask and let char letter = the letter corresponding to the element I want. How do I get from the letter corresponding to the element I want to the value of that element of the structure?

I cannot use output=color.letter as the structure has no element named 'letter' rather an element of the field with the same name as the value of letter. I could use something like

if (letter=='a') {output = color.a}
if (letter=='b') {output = color.b}
...many lines...
if (letter=='v') {output=color.v}

But I would like a better way. I have looked for ways using pointers but I do not think they work since I am using bit fields. I appreciate any help!


Solution

  • C does not provide dynamic selection of bit-fields or structure members. Your practical choices are generally to write your own access routines to select a field, likely using a switch rather than a series of if statements, or to manipulate the bits using bit-shift operators such as <<, >>, &, and |.