Bit Field in C
Bit Field in C
In C, we can specify size of structure and union members in bits to optimize memory space. The idea is to
use memory efficiently when we know that the value of a field or group of fields will never exceed a limit
or is within a small range. For example, we know that day value of a date cannot exceed 31, month of
date cannot exceed 12, etc.
#include <stdio.h>
// A simple representation of the date
struct date {
unsigned int d : 5;
unsigned int m : 5;
unsigned int y;
};
int main()
{
printf("Size of date is %lu bytes\n", sizeof(struct date));
struct date dt = { 31, 12, 2014 };
printf("Date is %d/%d/%d", dt.d, dt.m, dt.y);
}
Output:
Size of date is 8 bytes
Date is 31/12/2014
In the above code the structure requires 8 bytes of memory space for ‘dt’ variable, but only 5 bits will be
used to store the values for ‘d’ and ‘m’ and 4 bytes for ‘y’.
1. A special unnamed bit field of size 0 is used to force alignment on next boundary.
2. We cannot have pointers to bit field members as they may not start at a byte boundary.
3. We can have static members in a structure/class, but bit fields cannot be static.
4. Array of bit fields is not allowed. For example, the below program fails in the compilation.