C - SPLessons

Chapter 27

Bit Field in C

Bit Field in C

Unfortunately, structure in C-language does not have the capability of reducing the memory space. This back drop can be achieved by using Bit Field in C code.

If the structure members are specified in terms of bits, then it is called as “bit-field”. They can be mainly used to increase the memory efficiency by giving a finite space to each member. Bit Field in C packs the data in a structure.


datatype  bit-field_name :(length of bit-field)

where, data-type should always be int (or) unsigned.

Eg:

struct book
{
unsigned author : 4
unsigned page: 1
unsigned subject :2
};

#include<stdio.h>
int main()
{
	 struct bitfield 
	{
		 unsigned a1:3;
		 unsigned a2:5;
		 unsigned a3:4;
	}bit;
	
	char *p;
	struct bitfield *ptr,bit1={1,3,3};
	p=&bit1;
	p++; 
	printf("%d",*p);
}

Output:

115

Summary

  • Bit fields increase the memory capability by considering the structure members size as the bits.
  • There are no default initializers for bit-fields.