Write about Bit Fields in C?


The number of bits required for the structure variable is equal to the sum of the number of bits required for reach field.

The structure allows us to specify the numbers of bits of memory to be allocated for its member fields such fields are called “Bit Fields”.

A bit field is a set of adjacent bits. Whose size can be from 1 to 16 bits in length . A word can be divided into a number of bit fields. The name and size of bits fields are defined using a structure.

The general form of bit field definition is:

struct  tag_name
{
datatype name1 : bit-length ;
datatype name2 : bit-length ;
-----------------------------------
-----------------------------------
datatype namen : bit-length;
}

The datatype is either int or unsigned int or signed int and the bit –length is the number of bits used for the specified name.

Note that the field name is followed by a colon. The bit length is decided by the range of value to be stored.

Ex: 

struct bit
{
unsigned int x : 5;
unsigned int y : 12;
unsigned int z :10;
}
k;

In the above example 5 bits are allocated for x, 12 for y and 10 for z. So the memory required for k is 27 bits. But memory is in the form of bytes. So 4 bytes are allocated for k.

The bit fields are used to save memory space. We can create effective data structures Using unions and bit fields.


Related

C Language 5710166465967569698

Post a Comment

emo-but-icon

item