Bit Fields in structure or union C language

 Bit Fields in C 


In C, we can specify size in bits for members of union and structures. With this feature it will be helpful for utilizing memory efficiently. 


When to use this feature?

for members in structure or union, we know the value has to be provided in fixed range. This range is known to us in advance. Value provided beyond this range will not be acceptable one. In such we can use Bit Fields for members in structure or union. Assume that we are working with date related program where day  range is from 1 to 31, month range is from 1 to 12.


How much bit fields must be provided for members ?

    In the above paragraph, day range is from 1 to 31, month range is from 1 to 12, based on these ranges check how many bits are required to store  this range of value. To do this you can follow simple rules like 2^4 means 2 x 2 x 2 x 2= 16 means you can represent a range of value from 1 to 16 in 4 bits of memory.  


for example


int day : 5; 

5 means 5 bits required to store day which ranges from 1 to 31, where as 2 ^ 5 means 2 x 2 x 2 x 2 x 2 = 32 our day maximum 31 is covered in 2 ^ 5 range. Hence 5 bits are enough to store day value. If we specify only,

                                int day;


1 int value takes say 4 bytes i.e. 32 bits. But for day value it is simply taking more memory if we use only int. hence write as follows to manage memory efficiently,

                                int day:5;


try out these following examples :


#include<stdio.h>

struct date

{

    int day;

    int month;

    int year;

};

main()

{

    printf("\nSize of one structure variable of type date is %d bytes",sizeof(struct date));

    struct date d={2, 10, 2021};

    printf("Date is %d / %d / %d ",d.day,d.month,d.year);

}

output :

Size of one structure variable of type date is 12 bytes

Date is 2 / 10 / 2021 


In the above output we see that date structure variable taking 12 bytes which is unnecessary extra. Hence we will rewrite the program as follows with bit fields,


#include<stdio.h>

struct date

{

     int day:5;

    int month:5;

    int year;

};

main()

{

    printf("\nSize of one structure variable of type date is %d bytes",sizeof(struct date));

    struct date d={2, 10, 2021};

    printf("Date is %d / %d / %d",d.day,d.month,d.year);


}

output :

Size of one structure variable of type date is 8 bytes

Date is 2 / 10 / 2021 


Now you see in above output it is taking only 8 bytes instead of 12 bytes so you have saved 4 bytes of memory. This is the reason to use BIT FIELDS in structure or unions.


 I hope you like this post, please share, like, comment. 

Happy Reading...





Comments