Bitwise operators
- C++ course
- Beginner
- Lesson 28/116
- 5 min
Learn bitwise operations with &, |, ^, ~, << and >>.
Bitwise operators
Bitwise operators work on the binary representation of integers bit by bit: & (and), | (or), ^ (xor), ~ (not), << (left shift), >> (right shift).
For example, 12 & 10: 12 = 1100, 10 = 1010, binary and → 1000 = 8. 12 | 10 → 1110 = 14.
<< and >> shift bits: 1 << 3 = 8 (1 shifts three positions left). It is faster than multiply/divide; common in flag operations.
Bitwise shift
The << and >> operators shift bits left or right. Each left shift multiplies by two: 5 << 1 = 10. Each right shift divides by two: 20 >> 1 = 10.
Shifting is a fast multiply/divide method but only for powers of two. x << 3 is the same as x * 8.
It is also used for flag operations: flags | (1 << 3) sets the 3rd flag, flags & ~(1 << 3) clears it. This pattern is common in low-level programming.
Practice Print bitwise results
Inside main, declare int a = 12; and int b = 10;. Perform two bitwise operations: int andResult = a & b; and int orResult = a | b;. Print both on separate lines with std::cout using std::endl.
Starter code
#include <iostream>
int main() {
// Declare a and b
// Do & and | operations and print them
return 0;
}Sample solution
#include <iostream>
int main() {
// Declare a and b
int a = 12;
int b = 10;
// Do & and | operations and print them
int andResult = a & b;
int orResult = a | b;
std::cout << andResult << std::endl;
std::cout << orResult << std::endl;
return 0;
}Expected output
8 14
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Bitwise and
int result = a ____ b;
int result = a & b;
Explanation: & is the bitwise and operator.
2 Match bitwise operators
| Term | Meaning |
|---|---|
& |
Bitwise and |
| |
Bitwise or |
^ |
Bitwise xor |
<< |
Left shift |
3 What is the result of 12 & 5?
- 4 Correct answer
- 17
- 60
- 0
Explanation: 12=1100, 5=0101, 12 & 5 = 0100 = 4.