- UNIT-I (Array)
strlen(),strcpy(),strcat() ,strcmp()
Definition
Macro substitution directives
File inclusion directives
Conditional compilation
Bitwise Operators
Shift operators
Masks
Bitfield
Macro substitution directives
File inclusion directives
Conditional compilation
Bitwise Operators
Shift operators
Masks
Bitfield
Bitfield
A bit field is a collection of adjacent bits is defined inside a structure but is different from other members because its size is specified int of bits. The data type of. a bit field can be int, signed int or unsigned int.
Syntax for bit field
struct struct-name
{
datatype var1 : size of bits;
datatype var2 : size of bits;
- - - - - - - - - -
- - - - - - - - - -
datatype varN : size of bits;
};
Let us take an example that shows the syntax of defining bit fields.
struct tag {
unsigned a:2;
unsigned b:5;
unsigned c:l;
uns{gned d: 3;
};
Here the structure has four-bit fields a, b, c, and d. The sizes of a, b, c and dare 2, 5, 1 and 3
respectively; The bit fields can be accessed like other members of the structure using the dot operator. Whenever they appear inside expressions, they are treated like integers(of smaller range). Some valid expressions using bit fields.
struct tag var;
var.a=2;
printf("%dn,var.bl);
x=var.a+var.b; "
if(var.c==11)
printf ("Flag is on\n);
If the size of a bit field is n, then the range of values that the bit field can take is from 0
Bitfield Size in bits Range of values
a 2 o to 22-1( 0 to 3)
b 5 o to 25-1 (0 to 31)
c 1 o to 21-1 ( 0 and 1)
d 3 o to 23-1 (0 to 7)
It would be invalid to assign any value to a bitfield outside its range, for example,
var.b = 54; /*Invalid*/
We can't apply size of and address operators to bit fields. So we can't use scanf to input in a bit field.
scanf("%d", &var.a);
may input the value into a temporary variable and then assign it to the bit field.
scanf("%d", &temp);
var.a = temp;
•we have a pointer to structure then arrow operator(-» )can be used to access the bit fields.
#include <stdio.h>
int main()
{
struct sample {
unsigned int b1;
unsigned int b2;
}s1;
struct sample2 {
unsigned int b1:1;
unsigned int b2:1;
}s2;
printf("Size of structure sample : %d ", sizeof(s1));
printf("\nSize of structure sample2 : %d ", sizeof(s2));
return 0;
}
- Size of structure sample: 8
- Size of structure sample2: 4
कोई टिप्पणी नहीं:
एक टिप्पणी भेजें