Search code examples
cbit-fields

Concept of bit field


struct A
{
 int a:2;
 int b:3;
 int c:3;
};

int main()
{
 struct A p = {2,6,1};
 printf("\n%d\n%d\n%d\n",p.a,p.b,p.c);
 return 0;
}    

Output is: -2,-2,1

What would be output of above code in C complier and in C++ complier? And Why?


Solution

  • Now Lets see what exactly is happening. Lets start with the given code:

    struct A
    {
     int a:3;
    };
    int main()
    {
     struct A p = {5};
     printf("%d",p.a);
    }
    

    within 3 bits the values would be 101(5) since sign bit of this 3 bit set is 1 thus negative value. Thus we need to find 2's compliment of 101 which would be 011(3). Thus by applying above logic we would output as -3. Similarly others could be proved.

    e.g. for 1001(9) we shall take 3 bit values because of a:3. thus it would be 001(1). Since here sign bit is not set i.e. 1 so no need to use 2's complement. Straight forward answer would be 1. Similarly others could be done.