Bitfields C

  • What are bitfields?
  • Using bitfields.

When the question of saving memory is at the priority, we can group variables requiring a few bits as a single word (i.e. single integer), instead of defining each variable as an integer or character. This can be done using bitfields

What are bitfields?
One-bit can give values (true/false). Value of 2-bits can range from 0 to 4. Value of 3-bits can range from 0 through 7. Several such data items can be combined into an individual word of memory. Such data items are called bit-fields are defined as members of structure.

In general

Each member name is followed by a semicolon and an unsigned integer indicating field size. Variable definition and accessing each member is same as ordinary structure.

Using bitfields
If we have to store the information of an employee like:

  • He/she can be male or female. One-bit will be sufficient for the purpose.
  • Can be single, married, divorced or widowed. two-bits are sufficient.
  • Can belong one of 8 different departments. three bits will do

Thus we declare the structure as

The number after the colon specifies the size of each bit-field. It is defined as a structure, which is subdivided into 3 bit fields. They have width of 1, 2 and 3. Hence they occupy 6 bits within a word of memory.


Let us write a small program using the given bitfield structure

//program demonstrating use of bitfields

Gender =0 Marital Status =1 Department =0
Requires: 4 bytes

Values are assigned to bitfields using #defines. Bitfields can also be initialized. Bitfields can appear in arithmetic expressions.
Arrays of bitfields are not allowed. The (&) address operator cannot be applied to a bitfield, pointer cannot access a bitfield and a function cannot return a bitfield.

A bitfield without a name can be used for padding.

};A bitfield without a name

A bitfield can be forced to start at a beginning of a new word by specifying unnamed bitfield of width 0.

beginning of a new word by specifying unnamed bitfield of width 0

Face Book Twitter Google Plus Instagram Youtube Linkedin Myspace Pinterest Soundcloud Wikipedia

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd Protection Status

C Topics