Question 1 Report
Study the following pseudocode that extracts individual bits from a byte value (0-255).
DECLARE Value : INTEGER
DECLARE Bits : ARRAY[1:8] OF INTEGER
DECLARE Position : INTEGER
DECLARE Temp : INTEGER
Value ← 173
Temp ← Value
FOR Position ← 8 TO 1 STEP -1
Bits[Position] ← Temp MOD 2
Temp ← Temp DIV 2
NEXT Position
FOR Position ← 1 TO 8
OUTPUT Bits[Position]
NEXT Position(a) Complete the trace table for Value = 173. [5]
| Position | Temp (before) | Temp MOD 2 | Bits[Position] | Temp DIV 2 |
|---|---|---|---|---|
| 8 | ||||
| 7 | ||||
| 6 | ||||
| 5 | ||||
| 4 | ||||
| 3 | ||||
| 2 | ||||
| 1 |
(b) Write down the binary representation of 173 from the output. [1]
(c) Explain why the loop goes from 8 down to 1 but the output loop goes from 1 to 8. [2]
(d) State what MOD 2 and DIV 2 achieve in this algorithm. [2]
(a) The algorithm converts a byte value (0-255) to its 8-bit binary representation by extracting bits from least significant to most significant. [5]
| Position | Temp (before) | Temp MOD 2 | Bits[Position] | Temp DIV 2 |
|---|---|---|---|---|
| 8 | 173 | 1 | 1 | 86 |
| 7 | 86 | 0 | 0 | 43 |
| 6 | 43 | 1 | 1 | 21 |
| 5 | 21 | 1 | 1 | 10 |
| 4 | 10 | 0 | 0 | 5 |
| 3 | 5 | 1 | 1 | 2 |
| 2 | 2 | 0 | 0 | 1 |
| 1 | 1 | 1 | 1 | 0 |
Each iteration extracts one bit using MOD 2 and shifts the remaining value right using DIV 2 [1].
(b) The binary representation of 173 is 10101101 [1].
Verification: 128 + 0 + 32 + 0 + 8 + 4 + 0 + 1 = 173.
(c) The extraction loop goes from position 8 down to 1 because MOD 2 extracts the least significant bit first, which belongs in the rightmost position. The bits are stored from Bits[8] backwards so that Bits[1] ends up holding the most significant bit [1]. The output loop goes from 1 to 8 to display the bits in the conventional left-to-right order (most significant bit first) [1].
(d) MOD 2 extracts the current least significant bit, yielding 0 or 1 [1]. DIV 2 performs integer division, which effectively shifts all remaining bits one position to the right, discarding the bit just extracted and exposing the next bit for the next iteration [1].
Everything you need to excel in your exams