Bitwise operators are used when we want to manipulate the individual bits in a bit pattern. You need to understand binary to follow this. There are 4 main operations,
The effect of these operations is shown in the truth tables below.
Takes only one input and returns the opposite. Sometimes this gate is referred to as an inverter.
Input A | Output |
0 | 1 |
1 | 0 |
Takes two inputs, the output is true if both inputs are true.
Input A | Input B | Output |
0 | 0 | 0 |
0 | 1 | 0 |
1 | 0 | 0 |
1 | 1 | 1 |
Takes two inputs, the output is true if either of the inputs is true.
Input A | Input B | Output |
0 | 0 | 0 |
0 | 1 | 1 |
1 | 0 | 1 |
1 | 1 | 1 |
The exclusive or gate takes two inputs. The output is true if one input is true but not both.
Input A | Input B | Output |
0 | 0 | 0 |
0 | 1 | 1 |
1 | 0 | 1 |
1 | 1 | 0 |
The following program performs a NOT operation on the variable a.
int a = 13;
int b = ~a;
Console.WriteLine(b);
Console.ReadLine();
The output you get from this program is -14. Let's see if that's what we should be expecting. We started with a value for a of 13. In binary this is,
00001101
If we invert each of these bits, we get the following,
11110010
In denary, this value is -128 + 64 + 32 + 16 + 2 = -14.
The following program performs an AND operation with the variables a and b.
int a = 13;
int b = 17;
int c = a & b;
Console.WriteLine(c);
Console.ReadLine();
The output you get from this program is 1. Is that right? The values for a and b are 13 and 17 respectively. In binary this is,
00001101
00010001
The AND opertion returns a bit only where the bits from both numbers are set to 1. The only bit this happens for is for the unit bit. The answer is therefore 1.
The following program performs an OR operation with the variables a and b.
int a = 13;
int b = 17;
int c = a | b;
Console.WriteLine(c);
Console.ReadLine();
The output from this program is 29. Is that what we expect? The values for a and b are 13 and 17 respectively. In binary this is,
00001101
00010001
The OR operation returns a bit if either or both of the bits are set to 1. In this case, this gives the new binary number,
00011101
This is equal to 16 + 8 + 4 + 1 = 29
The following program performs an XOR operation with the variables a and b.
int a = 13;
int b = 17;
int c = a ^ b;
Console.WriteLine(c);
Console.ReadLine();
The output from this program is 29. Is that what we expect? The values for a and b are 13 and 17 respectively. In binary this is,
00001101
00010001
The XOR operation returns a bit if either but not both of the bits are set to 1. In this case, this gives the new binary number,
00011100
This is equal to 16 + 8 + 4 = 28