The problem
A machine that stores whole numbers in w bits keeps only the lowest w bits of a result, and reads them as two’s complement: the top place (place w - 1) is worth minus 2 to the power w - 1. Return the number it ends up with for the whole number x.
wrap(200, 8) # -56: 11001000 is -128 + 72
wrap(127, 8) # 127
wrap(261, 8) # 5: only the lowest 8 bits stay
wrap(-129, 8) # 127
wrap(2 ** 31, 32) # -2147483648
x may be negative. Python’s bit operators treat a negative number as two’s complement with endless 1s on the left (lesson 1), so masks work on it directly.
Limits
wis from 1 to 200.xcan be any whole number, including very large and negative ones.
Builds on BITS-1 Binary and two’s complement.
Continue on a laptop
Practice runs Python in the browser and needs a keyboard and a wider screen. Read the problem and open hints here, then write your solution on a laptop. Progress is saved per browser for now, so hints opened here stay on this device.
Need a hint?0 of 3 opened
- Hint 1Nudge
- Hint 2Approach Open hint 1 first
- Hint 3Pseudocode Open hint 2 first
- Worked solutionlast resort Opens after all 3 hints
Ctrl + Enter runs the tests. Tab indents; press Esc, then Tab, to leave the editor.
| # | Test | Result | Reads · time |
|---|---|---|---|
| 1 | The example | Not run | |
| 2 | Top bit 0 | Not run | |
| 3 | Just past the top | Not run | |
| 4 | All ones | Not run | |
| 5 | Bits above the width | Not run | |
| 6 | Already negative | Not run | |
| 7 | Too negative | Not run | |
| 8 | One bit | Not run | |
| 9 | A 32-bit counter overflows | Not run | |
| 10 | A 32-bit product | Not run | |
| 11 | 64 bits | Not run | |
| 12 | Every value, 5 bits | Not run | |
| 13 | Minus one, very wide | Not run | |
| 14 | A huge number | Not run |