Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concept of bit field

Tags:

c

bit-fields

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?

like image 920
suraj.prasoon Avatar asked Dec 28 '22 01:12

suraj.prasoon


1 Answers

Your system seems to using 2's complement. A 2-bit bit-field holding 2 would be 10 in binary which is -2 in 2's complement system. Likewise 110(6) is -2 for a 3-bit representation in 2's complement. And 1 is plain 1

Also read about signed bit-fields here

like image 88
Pavan Manjunath Avatar answered Dec 29 '22 15:12

Pavan Manjunath