Bitwise operators are used to perform a bit-level operation on operands. They are used in testing, setting, or shifting the actual bits in a program.
You can see the truth table below.
p | q | p & q | p | q | p ^ q | ~p |
---|---|---|---|---|---|
0 | 0 | 0 | 0 | 0 | 1 |
0 | 1 | 0 | 1 | 1 | 1 |
1 | 1 | 1 | 1 | 0 | 0 |
1 | 0 | 0 | 1 | 1 | 0 |
Below are the list of Bitwise operators:
Operators | Name of operators |
---|---|
& | Bitwise AND |
| | Bitwise OR |
^ | Bitwise XOR |
~ | Bitwise complement |
<< | Shift left |
>> | Shift right |
Example of C# Bitwise Operators
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | using System; namespace Operator { class Bitwise { static void Main(string[] args) { int a = 60; //60 = 0011 1100 int b = 13; //13 = 0000 1101 int result = 0; result = a &b; //12 = 0000 1100 Console.WriteLine("'&' Operator, Result: {0}", result); result = a | b; //61 = 0011 1101 Console.WriteLine("'|' Operator, Result: {0}", result); result = a ^ b; //49 = 0011 0001 Console.WriteLine("'^' Operator, Result: {0}", result); result = ~a; //-61 = 1100 0011 Console.WriteLine("'~' Operator, Result: {0}", result); result = a << 2; //240 = 1111 0000 Console.WriteLine("'<<' Operator, Result: {0}", result); result = a >> 2; //15 = 0000 1111 Console.WriteLine("'>>' Operator, Result: {0}", result); } } } |
Output:
1 2 3 4 5 6 | '&' Operator, Result: 12 '|' Operator, Result: 61 '^' Operator, Result: 49 '~' Operator, Result: -61 '<<' Operator, Result: 240 '>>' Operator, Result: 15 |