Lesson 2 · Unit 01
Whole numbers
Fixed widths, overflow, negatives and bit operators
What you practise
- Unsigned vs two's complement, overflow and wraparound in fixed-width ints, why Python's ints don't overflow,
&,|,^,<<,>>
Try a question from this lesson
Pick one
An old game keeps your score in a single byte, which holds 0 to 255. The score is 255 and you earn one more point. What does it show?
Correct answer
0
Why
There is no ninth bit to carry into, so the byte rolls over to 0, like a car odometer passing 999999. This is integer overflow. Nothing crashes: the wrong number is stored silently.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Negatives: two's complement
To store negative numbers, the top bit's place is made negative. In 8 bits the places are -128, 64, 32, 16, 8, 4, 2, 1.
All ones is -128 + 127 = -1. The range is -128 to 127. This scheme is called two's complement, and ordinary binary addition just works on it.
-128 64 32 16 8 4 2 1
1 1 1 1 1 1 1 1 = -1
1 0 0 0 0 0 0 0 = -128
0 1 1 1 1 1 1 1 = 127Concept
Python ints grow. Most do not.
Python's int has no fixed width: it adds more bits whenever it needs them, so it never overflows.
C, Java, Rust, databases and NumPy arrays use fixed widths (8, 16, 32 or 64 bits) because they are fast and compact. There, going past the top wraps around.
import numpy as np
print(2 ** 64) # a Python int: fine
tiny = np.array([255], dtype=np.uint8)
print(tiny + 1) # 8 bits: wraps to [0]10 more exercises in the app
- 4× type the answer
- 3× multiple choice
- 1× match the pairs
- 1× fill the blanks
- 1× true or false
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.