Search code examples
cbitbit-fields

Set and Reset of Bitfields


I am trying to write a C program wherein I will declare two variable of type status bitfield, status a and status mask.And in status a I can only set the bitfields which are already set in mask.

#include<stdio.h>

typedef struct
{
    unsigned int w : 1 ;
    unsigned int x : 1 ;
    unsigned int y : 1 ;
    unsigned int z : 1 ;
}status ;

void bitset(status* a,status* b,int position)
{
    /*Check for the position and set that bit only if it is set in mask.
     In this case, I can set only a.x and a.z.

}
int main()
{
    status a ;
    status mask ;
    int position ;

    mask.w = 0
    mask.x = 1 ;
    mask.y = 0;
    mask.z = 1;

    position = 1 ;

    bitset(&a,&b,position); 
}

For this I tried using & operator.But it is showing error.

Q1: By using pointers to the a and mask how can I complete the function bitset.

Q2: Is there a way so that I can set all the bitfields at once,something like a = 0x10 so that only y bit is set.

Q3: Is there a way so that I can reset all the bits at once,like a={0}.Is this the correct way to do it? Please help.


Solution

  • A2: not in a portable way; you can put it into a union with an integer member and shuffle the bitfields so that it works for your ABI. But as said, this is not portable

    A3: memset(&a, 0, sizeof a) should do it

    BUT: bitfields are ugly and probably the wrong choice for you use case. I would use unsigned integers for it.