Check The Programming Section
Another important bitwise operator is OR (|) operator, represented with signle pipe symbol. The rules that govern the value of the resulting bit obtained after ORing of two bits is shown in the Table below.
Using the above Table the ORing of two numbers of there bits are shown below:
10110011 Original bit pattern
11000011 OR Mask
--------
11110011 Resulting bit pattern
The Bitwise OR operator is usually used to put ON a particular bit in a number. For example, if a given bit pattern is 10010011 and if we want to ON the bit number 4 then the required OR mask will be 00010000. The idea is that the particular bit in the OR mask is set to ON and others will be in OFF. From the above Table now it is clear to us that, OR operation between a pair of bits will be always 1, if any of the given bits is ON and 0 if both the bits in a pair is OFF.
The bitwise XOR operator (^) also known as exclusive OR operator. XOR operator returns 1 only when any of the two bits is 1. The rules that govern the value of the resulting bit obtained after XOR of two bits is shown in the Table below.
Using the above Table the ORing of two numbers of there bits are shown below:
10110011 Original bit pattern
11000011 XOR bits
--------
01110000 Resulting bit pattern
The XOR operator is used to set a given bit to ON or OFF.
A number XORed with another number twice gives the original number.
Swapping the values of two variable without using a third variable.
#include<stdio.h>
int main(){
int a = 12;
int b = 13;
printf("Before Swapping a = %d, b = %d\n",a ,b);
a = a ^ b;
b = a ^ b;
a = a ^ b;
printf("After Swapping a = %d, b = %d\n", a, b);
}