Bitwise operators
Learn bitwise operations with &, |, ^, ~, << and >>.
Bitwise AND, OR and XOR
Bitwise operators work bit by bit on the binary representation of numbers. & is bitwise AND, | is bitwise OR, and ^ is bitwise XOR (exclusive or).
For example, 5 & 3: 5 = 101, 3 = 011, AND gives 001 = 1. 5 | 3 = 111 = 7. 5 ^ 3 = 110 = 6. These operators are common in flag handling.
Bitwise NOT and shifts
~ is bitwise NOT; it flips every bit. << is left shift, which moves bits left (multiplies the number by a power of two), and >> is right shift, which moves them right (divides by two).
For example, 1 << 3 returns 8: shifting 1 three places left gives 1000. 12 >> 2 = 11 = 3. Shifts are handy for building masks.
Exercise Shift a number right
Shift value right by 2 places (using the >> operator) and assign the result to shifted. Then print shifted with Console.WriteLine.
Show example solution
To shift right, write int shifted = value >> 2; and print it with Console.WriteLine.
Example solution:
using System;
class Program
{
static void Main()
{
int value = 12;
// Shift right and print
int shifted = value >> 2;
Console.WriteLine(shifted);
}
}
Test yourself
-
Match each operator to its meaning
- &
- Bitwise AND
- |
- Bitwise OR
- ^
- Bitwise XOR
- ~
- Bitwise NOT
-
What is the output of Console.WriteLine(5 & 3);?
Console.WriteLine(5 & 3);- 15
- 8
- 1
- 0
Show answer
1 — Correct. 5 (101) and 3 (011) give 001 = 1 with bitwise AND.
-
Write the right shift operator
int value = 12; int shifted = value ____ 2; Console.WriteLine(shifted);Show answer
int value = 12; int shifted = value >> 2; Console.WriteLine(shifted);