Bitwise Operators in C++

C++Server Side ProgrammingProgramming

There are 3 bitwise operators available in c++. These are the bitwise AND(&), bitwise OR(|) and the bitwise XOR(^).

The bitwise AND operator (&) compares each bit of the first operand to the corresponding bit of the second operand. If both bits are 1, the corresponding result bit is set to 1. Otherwise, the corresponding result bit is set to 0. Both operands to the bitwise inclusive AND operator must be of integral types. For example,

Example

#include <iostream>  
using namespace std;  
int main() {  
   unsigned short a = 0x5555;      // pattern 0101 ...  
   unsigned short b = 0xAAAA;      // pattern 1010 ...  
   cout << hex << ( a & b ) << endl;
}

Output

This gives the output −

0

The bitwise OR operator (|) compares each bit of the first operand to the corresponding bit of the second operand. If either bit is 1, the corresponding result bit is set to 1. Otherwise, the corresponding result bit is set to 0. Both operands to the bitwise inclusive OR operator must be of integral types. For example,

Example

#include <iostream>  
using namespace std;  
int main() {  
   unsigned short a = 0x5555;      // pattern 0101 ...  
   unsigned short b = 0xAAAA;      // pattern 1010 ...  
   cout << hex << ( a | b ) << endl;
}

Output

This gives the output −

ffff

The bitwise exclusive OR operator (^) compares each bit of its first operand to the corresponding bit of its second operand. If one bit is 0 and the other bit is 1, the corresponding result bit is set to 1. Otherwise, the corresponding result bit is set to 0. Both operands to the bitwise exclusive OR operator must be of integral types. For example,

Example

#include <iostream>  
using namespace std;  
int main() {  
   short a = 0x5555;      // pattern 0101 ...  
   unsigned short b = 0xFFFF;      // pattern 1111 ...  
   cout  << hex << ( a ^ b ) << endl;
}

Output

This gives the output −

aaaa

Which represents the pattern 1010...

raja
Published on 15-Feb-2018 09:41:30
Advertisements