Lesson 37: Bit shifts
Move the bits
- In lesson 22 four LEDs showed a number from 0 to 15 in binary. Now you move the bits: a shift.
- An LED that is on is a 1, an LED that is off is a 0.
- Each LED has a place value: 8, 4, 2 and 1. Add the values of the LEDs that are on.
- Together the four LEDs are a 4-bit register, like a tiny part of the computer's memory.
Words for this lesson
| Word | Meaning |
|---|---|
| register | a small store of bits inside a processor |
| place value | what a bit is worth: 8, 4, 2 or 1 |
| logical shift | move all the bits left or right; 0s come in |
| overflow | the answer needs more bits than the register has |
Read the LEDs
| LEDs (8 4 2 1) | Number |
|---|---|
| 0 1 0 1 | 4 + 1 = 5 |
| 1 1 0 1 | 8 + 4 + 1 = 13 |
| 1 1 1 1 | 8 + 4 + 2 + 1 = 15 |
Shifts
| Shift | Effect |
|---|---|
| left by 1 | × 2 |
| left by 3 | × 8 |
| right by 1 | ÷ 2 |
| right by 4 | ÷ 16 |
- Bits that move out of the register are lost. Then the answer is wrong.
In the exam
- 0478/12/M/J/23 Q2(b): a logical right shift of three places is done on a binary number. (i) Write the register after the shift. (ii) One effect: the number is divided by 8, and the bits on the right are lost, so the value can become inaccurate.
- 0478/12/F/M/24 Q8(c): the mathematical effect of a right shift of four places on a positive binary integer: it divides by 16.
Dificuldade 4/5 · Moedas 280 + pequeno bônus na primeira conclusão hoje
Four LEDs are a 4-bit register: pin 5 is worth 8, pin 4 is worth 4, pin 3 is worth 2 and pin 2 is worth 1. show(n) lights them. A logical right shift moves every bit one place to the right; a 0 comes in on the left. Start with value = 13 (1101). Each second, show the value, print Value: and the number, then shift: value = value >> 1. Do it 5 times.
Clique em Executar para ver a saída aqui.
Dificuldade 4/5 · Moedas 280 + pequeno bônus na primeira conclusão hoje
Now the other way. A logical left shift moves every bit one place to the left; a 0 comes in on the right. Start with value = 3 (0011). Each second, show the value, print Value: and the number, then shift: value = (value << 1) & 15. Do it 5 times. The & 15 keeps only 4 bits, so a bit that moves out on the left is lost.
Clique em Executar para ver a saída aqui.