The best programs are written so that computing machines can perform them quickly and so that human beings can understand them clearly. A programmer is ideally an essayist who works with traditional aesthetic and literary forms as
well as mathematical concepts, to communicate the way that an algorithm works and to convince a reader that the results will be correct. Donald E. Knuth

Bit Fields in C

Suppose we are required to declare a structure project with following variables :
1 ) status [ it can take three values ( started ( 0 ) , finished ( 1 ) , in_progress ( 2 ) ]
2 ) num_emp [ project can have 100 - 200 employees ]
3 ) type [ project can be either hardware ( 0 ) or software ( 1 ) ]
So, the structure can be defined as shown below.

struct project {
       unsigned int status;
       unsigned int num_emp;
       unsigned int type;
};

Above structure requires 12 bytes in memory ( single integer requires 4 ). However, we can observe that the variable status can take only three values and thus it requires maximum of 2 bits. Similarly, the variable num_emp requires maximum 8 bits and the variable type requires 1 bit only. So, the entire structure can actually be accommodated within 11 bits of memory i.e we won't require more than 2 bytes. Thus, one single integer provides sufficient storage for all the three variables. C provides a feature called bit fields which allows sharing the bits among multiple variables. Above structure can be modified to specify the width ( in terms of number of bits ) of each variable to utilize the memory space in a better way. The modified structure declaration is shown below.

struct project {
       unsigned int status  : 2;
       unsigned int num_emp : 8;
       unsigned int type;   : 1;
};
Run this program in your system to take input at run-time  

Now we need only 4 bytes of memory i.e all the information is packed into a single integer. We can declare more variables inside the structure shown above as still there will be more bits left. This variables can be referenced just like any other structure variable. Following program illustrates bit fields further.

#include <stdio.h>
#define STARTED 0
#define INPROGRESS 1
#define FINISHED 2
#define HARDWARE 0
#define SOFTWARE 1

typedef struct project {
       unsigned int status  : 2;
       unsigned int num_emp : 8;
       unsigned int type    : 1;
}proj_info;

int main() {
    proj_info p1;
    p1.status = STARTED;
    p1.num_emp = 151;
    p1.type = SOFTWARE;
    printf("Size of p1 = %ld bytes\n", sizeof(p1));
    printf("Contents of p1 :-\n");
    printf("Status : %d\n", p1.status);
    printf("Number of Employees : %d\n", p1.num_emp);
    printf("Project Type : %d\n", p1.type);
    return 0;
}

Back | Next