Integer Overflow and Two's Complement
Python's integers can grow as large as memory allows, but most languages and all CPUs store integers in a fixed number of bits: 8, 16, 32 or 64. A fixed width means there is a largest and a smallest value, and stepping past them makes the number wrap around. This lesson explains how negative numbers are stored (two's complement), why can become −128, and how to simulate it in Python.
A fixed number of bits
With bits there are exactly different patterns (see Powers of Two). Read as plain binary they cover 0 to . These are unsigned integers:
| Width | Patterns | Unsigned range |
|---|---|---|
| 8 bits (byte) | 0 … 255 | |
| 16 bits | 65 536 | 0 … 65 535 |
| 32 bits | 4 294 967 296 | 0 … 4 294 967 295 |
| 64 bits | 0 … 18 446 744 073 709 551 615 |
Add 1 to 11111111 and the true answer 1 0000 0000 needs nine bits. The ninth bit has nowhere to go and is dropped, leaving 00000000. So in 8 bits. That is overflow, and for unsigned numbers it is exactly arithmetic modulo (see Modular Arithmetic).
In Python, x & 0xFF keeps only the lowest 8 bits, which simulates an 8-bit register:
def u8(x):
return x & 0xFF # same as x % 256 for any int
print(u8(255 + 1), u8(200 + 100), u8(3 - 5))
print(u8(16 * 20), (16 * 20) % 256)0 44 254
64 64
Negative numbers: two's complement
To store negatives, almost every computer uses two's complement. In n bits, the top bit counts as instead of . For 8 bits the place values become:
place: −128 64 32 16 8 4 2 1
01111111 = 64+32+16+8+4+2+1 = 127 (largest)
10000000 = −128 = −128 (smallest)
11111111 = −128+64+32+16+8+4+2+1 = −1
11111011 = −128+64+32+16+8 +2+1 = −5So a signed -bit integer runs from to : from −128 to 127 for 8 bits and from −2 147 483 648 to 2 147 483 647 for 32 bits. There is one more negative number than positive, because zero takes one of the non-negative patterns.
To negate a number by hand: flip every bit, then add 1.
5 = 00000101
flip 11111010
+1 11111011 = −5 ✓The trick works because a number plus its flipped self is all ones, which is −1. So , and adding 1 gives . The same adder circuit then handles both signed and unsigned numbers: only the reading of the top bit differs.
def to_signed(x, bits=8):
x &= (1 << bits) - 1 # keep the low `bits` bits
return x - (1 << bits) if x >> (bits - 1) else x # top bit set -> negative
for v in [5, -5, -1, 127, -128]:
pattern = format(v & 0xFF, "08b")
print(f"{v:>5} -> {pattern} -> back: {to_signed(int(pattern, 2))}")
print("127 + 1 =", to_signed(127 + 1))
print("-128 - 1 =", to_signed(-128 - 1))
print("100 + 100 =", to_signed(100 + 100)) 5 -> 00000101 -> back: 5
-5 -> 11111011 -> back: -5
-1 -> 11111111 -> back: -1
127 -> 01111111 -> back: 127
-128 -> 10000000 -> back: -128
127 + 1 = -128
-128 - 1 = 127
100 + 100 = -56
Think of the 256 patterns as positions on a clock face: walking one step past 127 lands on −128.
32-bit wraparound and NumPy
The same function with bits=32 shows the famous limit . NumPy arrays use fixed-width integers, so they wrap silently. (Python's own int never overflows, it just gets bigger.)
import numpy as np
def to_signed(x, bits):
x &= (1 << bits) - 1
return x - (1 << bits) if x >> (bits - 1) else x
big = 2**31 - 1
print("Python int :", big + 1)
print("simulated :", to_signed(big + 1, 32))
a = np.array([big, 50_000], dtype=np.int32)
print("NumPy int32:", a + 1, " squares:", a[1:] * a[1:])
print("int32 range:", np.iinfo(np.int32).min, np.iinfo(np.int32).max)
print("50000² really is", 50_000**2)Python int : 2147483648
simulated : -2147483648
NumPy int32: [-2147483648 50001] squares: [-1794967296]
int32 range: -2147483648 2147483647
50000² really is 2500000000
Note: In the browser playground (Pyodide), NumPy's default integer type is int32, so
np.array([50_000]) ** 2overflows here even though it would not on a 64-bit desktop. Passdtype=np.int64when values can get large.
In software
Overflow causes real bugs:
- Game counters and scores stored in 8 or 16 bits wrap around. Old arcade games show a garbled level after level 255 for this reason.
- Timestamps. Unix time in a signed 32-bit integer runs out on 19 January 2038 (the "Year 2038 problem").
- Binary search computing
(lo + hi) / 2in 32-bit arithmetic can overflow for huge arrays.lo + (hi − lo) / 2avoids it (see Binary Search). - Security. An overflowed length or size can make a program allocate a tiny buffer and then write past it.
- Hash functions and random number generators use wraparound on purpose: unsigned 32- or 64-bit arithmetic modulo is fast and well defined.
In C, unsigned overflow is defined to wrap, but signed overflow is undefined behaviour: the compiler may assume it never happens. Rust panics on overflow in debug builds and offers wrapping_add when you want the wrap.
Exercises
Exercise 1: Ranges
What are the smallest and largest values of a signed 16-bit integer and of an unsigned 16-bit integer?
Answer
Signed: −32 768 to 32 767. Unsigned: 0 to 65 535.
Solution
Exercise 2: Encode a negative number
Write −20 as an 8-bit two's complement pattern using "flip and add 1".
Answer
11101100
Solution
20 = 00010100
flip = 11101011
+1 = 11101100
check: −128 + 64 + 32 + 8 + 4 = −20 ✓print(format(-20 & 0xFF, "08b"))11101100
Exercise 3: Predict the wrap
In signed 8-bit arithmetic, what is ? And in unsigned 8-bit, what is ?
Answer
(signed); (unsigned).
Solution
Every wrap moves the result by a multiple of until it is back in range.
Exercise 4: A 16-bit score counter
Write add_u16(a, b) that adds two scores the way an unsigned 16-bit register would, and show what happens when 60 000 points are added to a score of 10 000.
Answer
add_u16(10000, 60000) gives 4464.
Solution
Keep the low 16 bits with the mask 0xFFFF: .
def add_u16(a, b):
return (a + b) & 0xFFFF
print(add_u16(10_000, 60_000), add_u16(100, 200))4464 300
Test yourself
What is the range of a signed 8-bit two's complement integer?
- 0 to 255
- −127 to 127
- −128 to 127
- −256 to 255
In 8-bit two's complement, what number is 11111111?
- 255
- −1
- −127
- −128
Which Python expression keeps only the lowest 8 bits of x, like an unsigned byte?
- x | 0xFF
- x >> 8
- x & 0xFF
- x ^ 0xFF