Sunday, Nov 18th

Last update12:59:40 PM GMT

What are bit fields in structures?

Write e-mail

To avoid wastage of memory in structures, a group of bits can be packed together into an integer and its called a bit field.


	struct tag-name

	{

	    data-type name1:bit-length;

	    data-type name2:bit-length;

	    ...

	    ...

	    data-type nameN:bit-length;

	}

	


A real example


	struct student;

	{

	   char name[30];

	   unsigned sex:1;

	   unsigned age:5;

	   unsigned rollno:7;

	   unsigned branch:2;   

	};

	

	struct student a[100];

	

	scanf("%d", &sex);

	a[i].sex=sex;

	


There are some limitations with respect to these bit fields, however:

1. Cannot scanf() directly into bit fields.
2. Pointers cannot be used on bit fields to access them.
3. Cannot have an array of bit fields.


The main use of bitfields is either to allow tight packing of data or to be able to specify the fields within some externally produced data files. C gives no guarantee of the ordering of fields within machine words, so if you do use them for the latter reason, you program will not only be non-portable, it will be compiler-dependent too. The Standard says that fields are packed into ?storage units?, which are typically machine words. The packing order, and whether or not a bitfield may cross a storage unit boundary, are implementation defined. To force alignment to a storage unit boundary, a zero width field is used before the one that you want to have aligned. Be careful using them. It can require a surprising amount of run-time code to manipulate these things and you can end up using more space than they save. Bit fields do not have addresses?you can't have pointers to them or arrays of them. 
argaiv1879

Share this post



Web Hosting