In a C programming language Bitwise operator works on bits and perform bit-by-bit operation. There are following bitwise operators in C:-
| Operator | Description | Example |
|---|---|---|
| & | Binary AND Operator | a & b |
| | | Binary OR Operator | a| b |
| ^ | Binary XOR Operator | a^b |
| ~ | Binary One’s Complement Operator is unary | ~a |
| << | Binary Left Shift Operator | a<<b |
| >> | Binary Right Shift Operator | a>>b |
The truth tables for &, |, and ^ is as follows –
| a | b | a & b | a | b | a ^ b |
|---|---|---|---|---|
| 0 | 0 | 0 | 0 | 0 |
| 0 | 1 | 0 | 1 | 1 |
| 1 | 1 | 1 | 1 | 0 |
| 1 | 0 | 0 | 1 | 1 |
Assume A = 60 and B = 13 in binary format, they will be as follows −
A in binary = 0011 1100 (60)
B in binary = 0000 1101 (13)
Bitwise AND (&)
A = 0011 1100 (60)
& B = 0000 1101 (13)
———————————————————
0000 1100 (12)
Bitwise OR (|)
A = 0011 1100 (60)
| B = 0000 1101 (13)
———————————————————
0011 1101 (61)
Bitwise XOR (|)
A = 0011 1100 (60)
^ B = 0000 1101 (13)
———————————————————
0011 0001 (49)
Binary Left Shift Operator
Left shift operator shift all the bits in a left direction to specified number of times.
i=16 //0001 0000
i = i <<2; // 0100 0000 (shift left 2 bits, front 2 bits will be lost and appended 2 zero
Example:
#includeint main() { int i = 16; // 0001 0000 i = i>>2; // 0000 0100 (shift right 2 bits, last 2 bits will be lost, and 2 zero add in front) printf("i = %d", i); return 0; }
i=64
Binary Right Shift Operator
Left shift operator shift all the bits in a left direction to specified number of times.
int i = 16; // 0001 0000
i = i>>2; // 0000 0100 (shift right 2 bits, last 2 bits will be lost, and 2 zero add in front)
Example
#includeint main() { int i = 16; // 0001 0000 i = i>>2; // 0000 0100 (shift right 2 bits, last 2 bits will be lost, and 2 zero add in front) printf("i = %d", i); return 0; }
Output
i=4
Exapmle: Write a program to demonstrate Bitwise operator.
#includeint main() { int a = 60; int b = 13; int c, d, e, f, g, h; c = ~a; //c = -61 d = a | b; //d= 61 e = a & b; // e= 12 f = a ^ b; //f= 49 printf("\n value of c = %d", c); printf("\n value of d = %d", d); printf("\n value of e = %d", e); printf("\n value of f = %d", f); g = h = 16; g = g << 2; //g= 64 h = h >> 2; // h=4; printf("\n value of g = %d", g); printf("\n value of h = %d", h); }
OUTPUT
value of c = -61 value of d = 61 value of e = 12 value of f = 49 value of g = 64 value of h = 4