[prev] 80 [next]

Bit Fields

We can specify size (in bits) of structure and union members.

struct date{
   //day has value between 1 and 31
   //so 5 bits are sufficient
   unsigned int day: 5;
   //month has value between 1 and 12, 
   //so 4 bits are sufficient 
   unsigned int month: 4;
   unsigned int year;
};

int main(void) {
   printf("%lu bytes\n", sizeof(struct date));
   struct date d = {31, 12, 2014};
   printf("%d/%d/%d", d.day, d.month, d.year);
   return 0;
}