bitwise operators


The following table lists the Bitwise operators that C# supports. Assume variable A has a value of 60 and variable B has a value of 13.

Operator Description Example
& If a bit exists in both operands, the binary AND operator transfers it to the result. (A & B) = 12, which is 0000 1100
| If a bit exists in both operands, the binary OR operator duplicates it. (A | B) = 61, which equals 0011 1101, and B) = 12, which equals 0000 1100.
^ If a bit is set in one operand but not both, the binary XOR operator duplicates it. (A ^ B) = 49, which is 0011 0001
~ The Binary Ones Complement Operator is a unary operator that 'flips' bits. (~A ) = -61, which is 1100 0011 in 2's complement due to a signed binary number.
< < Left Shift Operator in Binary. The value of the left operand is shifted to the left by the number of bits provided by the right operand. A << 2 = 240, which is 1111 0000
> > Right Shift Operator in Binary. The value of the left operand is advanced by the number of bits given by the right operand. A >> 2 = 15, which is 0000 1111

Example

#include <iostream> using namespace std; int main() { int a = 60; /* 60 = 0011 1100 */ int b = 13; /* 13 = 0000 1101 */ int c = 0; c = a & b; /* 12 = 0000 1100 */ cout<<"\nLine 1 - Value of c is "<<c ; c = a | b; /* 61 = 0011 1101 */ cout<<"\nLine 2 - Value of c is "<<c; c = a ^ b; /* 49 = 0011 0001 */ cout<<"\nLine 3 - Value of c is "<<c; c = ~a; /*-61 = 1100 0011 */ cout<<"\nLine 4 - Value of c is "<<c; c = a << 2; /* 240 = 1111 0000 */ cout<<"\nLine 5 - Value of c is "<<c; c = a >> 2; /* 15 = 0000 1111 */ cout<<"\nLine 6 - Value of c is " <<c; return 0; }

OUTPUT:

string type

When the preceding code is built and run, the following result is obtained:

Line 1: c's value is 12; Line 2: c's value is 61; Line 3: c's value is 49; Line 4: c's value is -61 Line 5: c's value is 240; Line 6: c's value is 15