[edit] The & (AND) Operator
This section will teach you the basics of the C# & and | operators.
If we want to & the numbers 5 and 4 we simply compare each bit in the first number with each bit in the second number. Here is a chart for &
Note: When you compare each bit make sure they share the same position.
& Bit Comparison Chart
|
First Number |
Second Number |
Result & |
|
1 |
1 |
1 |
|
1 |
0 |
0 |
|
0 |
1 |
0 |
|
0 |
0 |
0 |
Now lets compare two numbers. We will compare numbers 4 and 5. Refer to the chart above to compare the bits.
5 = 1 0 1
4 = 1 0 0
------------
1 0 0
Starting from the left:
- Position 1: 1
- Position 2: 0
- Position 3: 0
The answer:
1 0 0 = 4
Code:
using System;
class Test
{
static void Main()
{
int a = 5;
int b = 4;
Console.WriteLine(a & b);
Console.Read();
}
}
Output:
[edit] The | (OR) Operator
Here is the chart for the | operator:
| Bit Comparison Chart
|
First Number |
Second Number |
Result | |
|
1 |
1 |
1 |
|
1 |
0 |
1 |
|
0 |
1 |
1 |
|
0 |
0 |
0 |
Now lets compare two numbers. We will compare numbers 4 and 5. Refer to the chart above to compare the bits.
5 = 1 0 1
4 = 1 0 0
------------
1 0 1
Starting from the left:
- Position 1: 1
- Position 2: 0
- Position 3: 1
The answer:
1 0 1 = 5
Code:
using System;
class Test
{
static void Main()
{
int a = 5;
int b = 4;
Console.WriteLine(a | b);
Console.Read();
}
}
Output:
|