Show understanding of and perform binary shifts
4.3 Bit Manipulation 🚀
🔍 What is Bit Manipulation?
Bit manipulation is like playing with LEGO bricks, but each brick is a single 0 or 1. By moving, adding, or removing these bricks we can change numbers in clever ways.
🔄 Binary Shifts
Shifting moves all bits left or right, just like sliding a row of dominoes.
- Left shift (<<) moves bits to the left, adding zeros on the right.
- Right shift (>>) moves bits to the right, discarding bits on the right.
🔢 Left Shift Example
Take the 8‑bit number 0001 0101 (decimal 21). Shift left by 2 positions:
0001 0101 << 2 = 0101 0100
In decimal, $21 \times 2^2 = 84$.
🔢 Right Shift Example
Take 0101 0100 (decimal 84). Shift right by 3 positions:
0101 0100 >> 3 = 0000 1010
In decimal, $84 \div 2^3 = 10$.
⚖️ Arithmetic vs Logical Shift
When shifting right, the sign bit (leftmost bit) can be preserved (arithmetic) or replaced with 0 (logical).
| Number (8‑bit) | Arithmetic Right Shift (>>) | Logical Right Shift (>>>) |
|---|---|---|
| 1111 1100 (decimal -4) | 1111 1111 (decimal -1) | 0000 0111 (decimal 7) |
💡 Practical Uses
- Fast multiplication/division by powers of two.
- Bit masks for setting, clearing, or toggling specific bits.
- Efficient algorithms in graphics and cryptography.
📝 Quick Quiz
What is the result of 1010 0011 << 1?
- A) 0100 0110
- B) 1010 0110
- C) 0100 1100
- D) 1010 0011
Answer: B (shift left adds a 0 on the right).
📌 Summary
Shifting is a powerful tool that lets you multiply or divide by 2, 4, 8… instantly, and it’s a key part of many low‑level programming tricks.
Revision
Log in to practice.