What is bit field operator?
Explain with example MCA solved c Programming Exam Question 2013-2014, What is bit field operator , bit field operator in c
What is bit field operator? Explain with example.
What is bit field operator? Explain with example.
The declaration of a bit-field has
the form inside a structure:
struct
{
type [member_name] : width ;
};
Below the description of variable
elements of a bit field:
The declaration of a bit-field has the form inside a structure:
Elements
|
Description
|
type
|
An integer type that determines how the bit-field's value
is interpreted. The type may be int, signed int, unsigned int.
|
member_name
|
The name of the bit-field.
|
width
|
The number of bits in the bit-field. The width must be
less than or equal to the bit width of the specified type.
|
The variables defined with a
predefined width are called bit fields. A bit field can hold more than a
single bit for example if you need a variable to store a value from 0 to 7 only
then you can define a bit field with a width of 3 bits as follows:
struct
{
unsigned int age : 3;
} Age;
The above structure definition
instructs C compiler that age variable is going to use only 3 bits to store the
value, if you will try to use more than 3 bits then it will not allow you to do
so. Let us try the following example:
#include
#include
struct
{
unsigned int age : 3;
} Age;
int main( )
{
Age.age = 4;
printf( "Sizeof( Age ) : %d\n", sizeof(Age) );
printf( "Age.age : %d\n", Age.age );
Age.age = 7;
printf( "Age.age : %d\n", Age.age );
Age.age = 8;
printf( "Age.age : %d\n", Age.age );
return 0;
}
When the above code is compiled it
will compile with warning and when executed, it produces the following result:
Sizeof( Age ) : 4
Age.age : 4
Age.age : 7
Age.age : 0