Nearby lessons
31 of 124C - Bitwise Operators
Bitwise Operators is one of the foundational topics in C programming. This lesson explains Bitwise Operators — Working on Binary Bits with complete, runnable code examples, clear step-by-step explanations, and common mistakes to avoid with exam-style MCQs at the end.
Bitwise Operators — Working on Binary Bits
Bitwise operators work on the binary bits of a number. They are used in system-level programming (flags, permissions, graphics, compression). Beginners should know they exist, but not worry about them too early.
| Operator | Meaning |
|---|---|
| & | Bitwise AND |
| | | Bitwise OR |
| ^ | Bitwise XOR |
| ~ | Bitwise NOT (ones complement) |
| << | Shift bits left |
| >> | Shift bits right |
AND, OR, XOR — How the Bits Behave
The three bit-by-bit rules to remember:
| Operator | Rule |
|---|---|
| AND (&) | 1 & 1 = 1, everything else is 0 |
| OR (|) | 0 | 0 = 0, everything else is 1 |
| XOR (^) | Same bits give 0, different bits give 1 |
Truth Tables — AND, OR, XOR and NOT
A truth table shows the result of an operator for every possible combination of bits. These four tables are the complete behaviour of the bitwise operators:
| A | B | A & B (AND) |
|---|---|---|
| 0 | 0 | 0 |
| 0 | 1 | 0 |
| 1 | 0 | 0 |
| 1 | 1 | 1 |
| A | B | A | B (OR) |
|---|---|---|
| 0 | 0 | 0 |
| 0 | 1 | 1 |
| 1 | 0 | 1 |
| 1 | 1 | 1 |
| A | B | A ^ B (XOR) |
|---|---|---|
| 0 | 0 | 0 |
| 0 | 1 | 1 |
| 1 | 0 | 1 |
| 1 | 1 | 0 |
| A | Result (~A / NOT) |
|---|---|
| 0 | 1 |
| 1 | 0 |
Shift Operators — << and >>
Shifting moves all the bits left or right. Each shift left multiplies by 2; each shift right divides by 2:
- Bitwise operators work on the binary bits of a number, not the number itself.
- & AND, | OR, ^ XOR, ~ NOT, << shift left, >> shift right.
- AND truth table: 1 & 1 = 1, everything else is 0.
- OR truth table: 0 | 0 = 0, everything else is 1.
- XOR truth table: same bits give 0, different bits give 1.
- NOT (~) flips every bit: ~0 = 1 and ~1 = 0.
- Shift left (<<) multiplies by 2; shift right (>>) divides by 2.
- Used in system-level programming — beginners should know they exist.