• admin@embedclogic.com

Bit Field in C

The concept of ‘Bit Field’ is used when we know the fixed length or range of values held by the structure member. Normally we use the primitive data type like char, int, short to decide the maximum and minimum value of the variable but sometimes we know about the exact length of data which is very less than assigned space by primitive data type then we can save memory by utilizing the concept of the bit field.

suppose you want to store your birth date i.e. date, month, year.

date      <=31———–> maximum 5 bit required.

month <=12——- —> maximum 4 bit required

year    <=2017(assume)—>maximum 12 bit required.

see this table to compare the bit field and non-bit field structure

structure memberWithout Bit FieldWith Bit Field
date unsigned int dateunsigned int date :5
monthunsigned int monthunsigned int month :4
yearunsigned int yearunsigned int year :12
Total space occupied in memory 12 byte4 byte

So from the above table, we can conclude that bit field plays a very important role where memory is very limited.

Bit field use: operator to bound a variable in fixed length.

Bit field syntax :

To understand this article, I assume that you are familiar with structure concept.let’s take a structure for your birth date.

12-byte space is reserved due to 3 unsigned int variable while the actual data requires only 17 bit. we can optimize the size using bit field concept in the above structure.

Note: Although the required memory is 17 bit in above structure space occupied by this structure is 4 byte i.e. 32 bit because minimum memory occupied by an integer is 4 byte on a 32-bit processor.

so if the size of the structure is <32 bit then it will automatically reserve 32-bit space.

As seen in the second structure all three members are packed into 32-bit space instead of occupying 32 bit each. we have bounded all member on their fixed length as explained in the table.

Sample Code:
 Points to remember about Bit Field:
  1. We can’t find the address of bit field member because they may not start from byte boundary.
  1. We can use zero length data member without a name in bit field structure for further data alignment at next boundary.

Note: If you are using multiple times continues jump then it will consider only once.

  1. Length of bit-field cannot exceed from its data type.
  1. An array of the bit field is not allowed.

Although I have tried to cover most of the part related to this topic your suggestion and comment is always welcome to improve this article. I also request you to send me if you find any error in this article .thank you so much for reading 🙂.