C Programming - SPLessons
SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

Bit Field in C

Bit Field in C

shape Description

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.

shape Syntax

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 };

shape Example

[c] #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); }[/c] Output: [c] 115[/c]

Summary

shape Key Points

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