The perfect place for easy learning...

C Programming Language

×

Topics List

Place your ad here

Bit Fields in C

When we use structures in the c programming language, the memory required by structure variable is the sum of memory required by all individual members of that structure. To save memory or to restrict memory of members of structure we use bitfield concept. Using bitfield we can specify the memory to be allocated for individual members of a structure. To understand the bitfields, let us consider the following example code...

Date structure in C

struct Date
{
    unsigned int day;
    unsigned int month;
    unsigned int year;
} ;

Here, the variable of Date structure allocates 6 bytes of memory.


In the above example structure the members day and month both does not requires 2 bytes of memory for each. Becuase member day stores values from 1 to 31 only which requires 5 bits of memory, and the member month stores values from 1 to 12 only which required 4 bits of memory. So, to save the memory we use the bitfields.
Consider the following structure with bitfields...

Date structure in C

struct Date
{
    unsigned int day : 5;
    unsigned int month : 4;
    unsigned int year;
} ;

Here, the variable of Date structure allocates 4 bytes of memory.


Place your ad here
Place your ad here