C: Bit Fields
In C, we can specify size (in bits) of structure and union members. 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 withing a small range. For example, consider the following declaration of date without the use of bit fields.
#include <stdio.h> // A simple representation of the date struct date { unsigned int d; unsigned int m; 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); }Using a compiler where an unsigned int takes 4 bytes, the result showed that the stucture ‘date’ takes 12 bytes:
Size of date is 12 bytes Date is 31/12/2014
Since we know that the value of d is always from 1 to 31, the value of m is from 1 to 12, we can optimize the space using bit fields:
#include <stdio.h> // Space optimized representation of the date struct date { // d has value between 1 and 31, so 5 bits // are sufficient unsigned int d : 5; // m has value between 1 and 12, so 4 bits // are sufficient unsigned int m : 4; 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); return 0; }the result showed that the stucture ‘date’ takes 8 bytes:
Size of date is 8 bytes Date is 31/12/2014
留言