Bitfields:
It is a user defined type used to allocate the memory in
bits.
For example if we want to store the date then it takes 5
bits to store the date, 4 bits to store the month and 10 bits to store the
year. Totally it needs 19 bits to store the date.
Without bitfields it takes 48 bits that is 3 integers to
store the date which results wastage of memory.
It is used to effectively use the memory.
Example:
#include<stdio.h>
struct date
{
unsigned dd:5; /* 5 bits memory allocation */
unsigned mm:4; /* 4 bits memory allocation */
unsigned
yyyy:11; /* 11 bits memory
allocation */
};
void main()
{
struct date
x={25,8,2005};
clrscr();
printf("%d/%d/%d",x.dd,x.mm,x.yyyy);
printf("\nSize
of x %d bytes",sizeof(x));
getch();
}
Output:
25/8/2005
size of x 3 bytes
Example explained:
In the above example it takes 20 bits to store the date.
Note: We can't specify the address of bitfield, Hence we
can't access the data int a bitfiled using scanf() function.
Bitwise operators:
These are the operators used to perform bitwise operations
on data.
These operators are used to perform low level operations in
developing low level applications.
These are also used to implement encryption and decryption
algorithms to enforce data security.
C language supports the following bitwise operators.
Operator |
meaning |
& |
AND bitwise operator |
| |
OR bitwise operator |
^ |
XOR bitwise operator |
~ |
1's compliment operator |
<< |
Left shift operator |
>> |
Right shift operator |
Truth table of bitwise operators:
A |
B |
A&B |
A|B |
A^B |
~A |
1 |
1 |
1 |
1 |
0 |
0 |
1 |
0 |
0 |
1 |
1 |
0 |
0 |
1 |
0 |
1 |
1 |
1 |
0 |
0 |
0 |
0 |
0 |
1 |
Example:
#include<stdio.h>
void main()
{
int a,b;
clrscr();
a=57;
a 1 1 0 1 0 1 53 b 1 1 1 0 0 0 56 a&b 1 1 0 0 0 0 48 a|b 1 1 1 1 0 1 61 a^b 0 0 1 1 0 1 13 a=a<<3 1 1 0 1 0 1 0 0 0 424 a=a>>3 1 1 0 1
0 1 53
b=64;
printf("a&b=%d",a&b);
printf("\na|b=%d",a|b);
printf("\na^b=%d",a^b);
a=a<<3;
printf("\na=%d",a);
a=a>>3;
printf("\na=%d",a);
getch();
}
Output:
a&b=48
a|b=61
a^b=13
a=424
a=53
<< Left shift operator:
It is a bitwise operator shifts all the bits towards left to
the specified number of places.
Fills 0's at the right side
Example:
>> Right shift operator:
It is a bitwise operator shifts all the bits towards right
to the specified number of places.
The shifted bits towards right will be automatically
deleted.
0 comments:
Post a Comment