Bitwise operator permit the programmer to access and manipulate individual bits within a piece of data. These operators can operate upon ints and chars but not on floats and doubles.
Bitwise operators
Operator | Meaning |
& | Bitwise AND |
| | Bitwise OR |
^ |
Bitwise XOR |
<< | Shift Left |
>> | Shift Right |
~ | Bitwise Complement (or) One's Complement |
Bitwise Operatot Truth Table
Bitwise Operator performs bit by bit operation.X | Y | X & Y | X | Y | X ^ Y |
0 | 0 | 0 | 0 | 0 |
0 | 1 | 0 | 1 | 1 |
1 | 0 | 0 | 1 | 1 |
1 | 1 | 1 | 1 | 0 |
Left Shift Operator
Consider the statementX=19;
Z=X<<2;
The value in the integer X is shifted left by two bit positions. The result is assigned to Z.The value of X is 0001 00112 the value of Z after the execution the value of Z is 0100 11002.
0001 00112 | Left Shift(2) |
0100 11002 | <-- Insert 2 Zero's (0) |
Right Shift Operator
Consider the statementX=19;
Z=X<<2;
The value in the integer X is shifted Right by two bit positions. The result is assigned to Z.The value of X is 0001 00112 the value of Z after the execution the value of Z is 0000 01002.
Right Shift(2) | 0001 00112 |
Insert 2 Zero's (0) --> | 0100 11002 |
Bitwise Complement Operator
operand must be of integral type. Each 0 bit in the operand is set to 1, and each 1 bit in the operand is set to 0.Consider the statement
X=19;
Z=~x;
X=0001 00112
Z=1110 11002
Bitwise operator Example:
#include<stdio.h>
int main()
{
int X=19,Y=16,Z;
Z=X&Y;
printf("X&Y=%d\n",Z);
Z=X|Y;
printf("X|Y=%d\n",Z);
Z=X^Y;
printf("X^Y=%d\n",Z);
Z=X<<2;
printf("X<<2=%d\n",Z);
Z=X>>2;
printf("X>>2=%d\n",Z);
Z=~X;
printf("~X=%d\n",Z);
return 0;
}
Output
X&Y=16X|Y=19
X^Y=3
X<<2=76
X>>2=4
~X=-20
Assume that X=19, Y=16, the binary format will be as follows.
X = 0001 00112 - 1910
Y = 0001 00002 - 1610
Binary | Decimal | |
X & Y | 0001 0000 | 1610 |
X | Y | 0001 00112 | 1910 |
X ^ Y | 0000 00112 | 310 |
X<<2 | 0100 11002 | 7610 |
X>>2 | 0000 01002 | 410 |
~X | 1110 11002 | -2010 |