C Pointers Question:
Download Questions PDF

What is the use of bit field?

Answer:

Packing of data in a structured format is allowed by using bit fields. When the memory is a premium, bit fields are extremely useful. For example:

- Picking multiple objects into a machine word : 1 bit flags can be compacted
- Reading external file formats : non-standard file formats could be read in, like 9 bit integers

This type of operations is supported in C language. This is achieved by putting :’bit length’ after the variable. Example:

struct packed_struct {
unsigned int var1:1;
unsigned int var2:1;
unsigned int var3:1;
unsigned int var4:1;
unsigned int var5:4;
unsigned int funny_int:9;
} pack;

packed-struct has 6 members: four of 1 bit flags each, and 1 4 bit type and 1 9 bit funny_int.

C packs the bit fields in the structure automatically, as compactly as possible, which provides the maximum length of the field is less than or equal to the integer word length the computer system.

The following points need to be noted while working with bit fields:

The conversion of bit fields is always integer type for computation
Normal types and bit fields could be mixed / combined
Unsigned definitions are important.

Download C Pointers Interview Questions And Answers PDF

Previous QuestionNext Question
Tell me what are bitwise shift operators?Explain what is the purpose of "extern" keyword in a function declaration?