Friday, July 29, 2016

C Basics - Structure Bit Fields in C

Bit field allows defining the width of a variable in a structure. It allows packing of data in a structure. C automatically packs the bit fields as compact as possible.
The declaration of a bit-field has the following form inside a structure −

struct {
   type [member_name] : width ;
};

For example,

struct reg {
   unsigned int b0:1;
   unsigned int b1:1;
   unsigned int b2_b3:2;
   unsigned int b4_b7:4;
};

Here, the structure contains 4 members: two 1 bit members to store value 0 or 1, one 2 bit member to store value from 0 to 4 and one 4 bit member to store value from 0 to 16.

#include <stdio.h>

struct reg {
   unsigned int b0:1;
   unsigned int b1:1;
   unsigned int b2_b3:2;
   unsigned int b4_b7:4;
};
int main( ) {
 
 struct reg control;
 
 printf( "sizeof(control):%d bytes\n", sizeof(control));
 return 0;
}
The output of the above program would be:

sizeof(control):4 bytes

The above structure requires 4 bytes of memory space for status variable, but only 8 bits will be used to store the values. The variables defined with a predefined width are called bit fields.

In the above structure, width of variable b4_b7 is 4 bits. If you try to use more than 4 bits, then the C compiler will not allow you to do so. The code will compile with a warning and when executed, it produces invalid results.



Related topics:
Structures in C   |   Structures and Function Parameters in C   |   Structures and Pointers in C   |   Union in C   |   Enumeration in C   |   Typedef in C

List of topics: C Programming

No comments:

Post a Comment