BITFIELDS:
A bitfield is a set of adjacent
bits whose size can be from 1 to 16 bits. Bit field provides exact amount of
bits required to store values i.e., for example when an integer is declared, 2
bytes are allocated to store an integer which we may or may not completely
utilize.
Therefore, to avoid wastage of memory, we
mention the exact bit size. The name and size of bit fields are defined using a
structure.
Syntax:-
struct tagname
{
datatype member 1:bit length;
datatype member 2:bit length;
:
:
datatype member n:bit length;
};
·
Here, the datatype can be either int or unsigned
int or signed int.
·
Bit length specifies the number of bits used
under that name.
·
Here the colon(:) tells the compiler that
bitfields are used in the structure.
·
In a bitfield of lenght1 we can store the values
0,1.
·
In a bitfield of lenght2 we can store the values
0,1,2,3.
·
Similarly, in a bit field of lenght1 we can
store the values 0,to 2n-1.
Ø A Program to implement bitfields.
#include<stdio.h>
#include<conio.h>
void main( )
{
struct
employee
{
unsigned empid:6;
unsigned
age:5;
unsigned
children:2;
}e1;
clrscr( );
e1.empid=59;
e1.age=29;
e1.children=2;
printf(“details
are\n”);
printf(“%u %u
%u”,e1.empid,e1.age,e1.children);
getch( );
}
No comments:
Post a Comment