Bit fields can be used in a structure or union. They are used where memory is very scarce. They can be used when the highest value that will be represented by a variable is very small.For instance, leat a variable int a is used to store 4 states say, (0, 1, 2, 3). The number of bits required to represent the highest value ‘3’ is 2. If an integer is used to save these states, 32 bits are allocates in which 30 bits are unused. If ‘n’ such variables are used, the number of bits wasted will be 30*n. By using bit fields represented as int a:2; Though complete 32 bits are allocated for the int type, a represents only the first two LSBs. Any further bitfields declared as in below example will be packed within this remaining 30 bits until the total size reaches above 32 bits (4 bytes).

#include <stdio.h>
int a:5;
int b:10;
int c: 12;
int d;
} n1;

int main()
n1.d = 0x12345678;
printf("a 0x%x b 0x%x c 0x%x d 0x%xn", n1.a, n1.b, n1.c, n1.d);


a 0xffff fff8 b 0xffff fe78 c 0x678 d 0x12345678

Leave a Reply

Your email address will not be published. Required fields are marked *