Bitwise Operators and their working with
Examples in C
1) & (bitwise AND)
It does AND on every bit of two numbers. The result of AND is 1 only if both
bits are 1.
Example:
4 & 7
4 → 00000100
7 → 00000111
Doing AND for each bit
From LSB:
0 & 1= 0 (LSB of output)
0 & 1= 0
1 & 1= 1
0 & 0 =0
0 & 0 =0
0 & 0 =0
0 & 0 =0
0 & 0 =0
Thus output:
00000100 → 4
4 & 7 =4
2) | (bitwise OR)
It takes two numbers as operands and does OR on every bit of two numbers.
The result of OR is 1 any of the two bits is 1.
Example:
4 | 7
4 → 00000100
7 → 00000111
Doing OR for each bit
From LSB:
0 | 1 =1 (LSB of output)
0 | 1 =1
1 | 1 =1
0 | 0 =0
0 | 0 =0
0 | 0 =0
0 | 0 =0
0 | 0 =0
Thus output:
00000111 → 7
4 | 7 =7
3) ^ (bitwise XOR)
It does XOR on every bit of two numbers. The result of XOR is 1 if the two
bits are different.
Example:
4 ^ 7
4 → 00000100
7 → 00000111
Doing XOR for each bit
From LSB:
0 ^ 1 =1 (LSB of output)
0 ^ 1 =1
1 ^ 1 =0
0 ^ 0 =0
0 ^ 0 =0
0 ^ 0 =0
0 ^ 0 =0
0 ^ 0 =0
Thus output:
00000011 → 3
4 ^ 7 =3