Tuesday 30 January 2018

Bit Fields in C

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.

----------------------------------------------------------------------------------------------------------------------------



----------------------------------------------------------------------------------------------------------------------------


                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.

----------------------------------------------------------------------------------------------------------------------------

 

----------------------------------------------------------------------------------------------------------------------------

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. 
 
----------------------------------------------------------------------------------------------------------------------------



----------------------------------------------------------------------------------------------------------------------------

 Output :
 
Size of p1 = 4 bytes
Contents of p1 :-
Status : 0
Number of Employees : 151
Project Type : 1

----------------------------------------------------------------------------------------------------------------------------

No comments:

Post a Comment