A bit field is term to store multiple, logical, neighboring bit, where each of the sets of bits, and single bits can be addressed. It is more addressed in C or C language by assigning bitfield to save the memory when we know that only limited number of bits are used in the program.
See the following example
struct
{
unsigned int isleft;
unsigned int isright;
} status;
Above structure will occupy the 2*size of int where we are only using the one bit of each field, so the solution is the bitfield -
struct
{
unsigned int isleft : 1;
unsigned int isright : 1;
} status;
Here we are telling the compiler only one bit (least significant) of each been used so to save memory while running.
Syntax
The declaration of a bit-field has the form inside a structure:
struct
{
type [member_name] : width ;
};
Below the description of variable elements of a bit field:
Elements |
Description |
type |
An integer type that determines how the bit-field's value is interpreted. The type may be int, signed int, unsigned int. |
member_name |
The name of the bit-field. |
width |
The number of bits in the bit-field. The width must be less than or equal to the bit width of the specified type.
|
Memory Comparison
Without BitField
#include <stdio.h>
struct my_str
{
unsigned int a;
unsigned int b;
unsigned int c;
};
int main()
{
printf("Size of my_str is %d bytes\n", sizeof(struct my_str));
}
Output
Size of my_str is 12 bytes
With Bit Field
#include <stdio.h>
struct my_str
{
unsigned int a : 1;
unsigned int b : 1;
unsigned int c : 1;
};
int main()
{
printf("Size of my_str is %d bytes\n", sizeof(struct my_str));
}
Output
Size of my_str is 4 bytes