Bit fields are partial size member variables inside a structure. Bit fields give flexibility to define some variables with less than the size or bit width of the original type. These are useful to save some numbers/parameters whose range is less than that of original type.

Let's take an example where we take a variable is_present of type Boolean. This can have only two values either true or false. Now considering the two possibilities we can say it can have a value of either 1 or zero which means only one bit is required to store this variable. Now if we use a Boolean or full size integer we are supposes to use only LSB and the rest 31 bits are unutilized. This can be optimized by defining a bit field of size 1 like "unsigned int is_present:1;"

Syntax:
struct <struct name>  {
  <type> <bit field name> : <bit width>;
  ...
};
Example:
struct bits_t  {
  unsigned int  bits2 : 2;
  unsigned int  bits3 : 3;
  unsigned int  pads  : 27;
};

One point to note here is unsigned integer of 1 bit has a range 0 to1. But this is not same for signed integer. Signed integer takes signature bit in MSB and magnitude in LSB side. Thus 1 bit signed integer has a range -1 to 0. 2 bit signed integer has -1 to +1. Similarly 2 bit and 3 bit signed integer have ranges like -2 to +1 and -4 to +3 accordingly. Below tables show these all combination bit patterns and corresponding signed values.

1 bit signed integer

Bit 0Value
1 -1
0 0

2 bit signed integer

Bit 1 Bit 0Value
1 0 -2
1 1 -1
0 0 0
0 1 +1

3 bit signed integer

Bit 2 Bit 1 Bit 0Value
100 -4
101-3
110 -2
111 -1
000 0
001 +1
010 +2
011 +3

About our authors: Team EQA

You have viewed 1 page out of 252. Your C learning is 0.00% complete. Login to check your learning progress.

#