BITS-P1

Wrap to w bits

Practice 1 of 5Bit manipulation14 tests

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

  • w is from 1 to 200. x can 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

  1. Hint 1Nudge
  2. Hint 2Approach Open hint 1 first
  3. Hint 3Pseudocode Open hint 2 first
  4. Worked solutionlast resort Opens after all 3 hints
Python waits for a wider screensolution.py

Ctrl + Enter runs the tests. Tab indents; press Esc, then Tab, to leave the editor.

14 tests, not run yet
Test results
#TestResultReads · time
1The exampleNot run
2Top bit 0Not run
3Just past the topNot run
4All onesNot run
5Bits above the widthNot run
6Already negativeNot run
7Too negativeNot run
8One bitNot run
9A 32-bit counter overflowsNot run
10A 32-bit productNot run
1164 bitsNot run
12Every value, 5 bitsNot run
13Minus one, very wideNot run
14A huge numberNot run