TExcelTAD
Home › Basic Math & Pre-Algebra › Integer Overflow and Two's Complement

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 127+1127 + 1 can become −128, and how to simulate it in Python.

A fixed number of bits

With nn bits there are exactly 2n2^n different patterns (see Powers of Two). Read as plain binary they cover 0 to 2n−12^n - 1. These are unsigned integers:

Width Patterns Unsigned range
8 bits (byte) 28=2562^8 = 256 0 … 255
16 bits 65 536 0 … 65 535
32 bits 4 294 967 296 0 … 4 294 967 295
64 bits ≈1.8×1019\approx 1.8 \times 10^{19} 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 255+1=0255 + 1 = 0 in 8 bits. That is overflow, and for unsigned numbers it is exactly arithmetic modulo 2n2^n (see Modular Arithmetic).

In Python, x & 0xFF keeps only the lowest 8 bits, which simulates an 8-bit register:

python · try it yourself
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 −2n−1-2^{n-1} instead of +2n−1+2^{n-1}. For 8 bits the place values become:

text
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      = −5

So a signed nn-bit integer runs from −2n−1-2^{n-1} to 2n−1−12^{n-1} - 1: 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.

text
 5  = 00000101
flip  11111010
+1    11111011  = −5 ✓

The trick works because a number plus its flipped self is all ones, which is −1. So flipped(x)=−1−x\text{flipped}(x) = -1 - x, and adding 1 gives −x-x. The same adder circuit then handles both signed and unsigned numbers: only the reading of the top bit differs.

python · try it yourself
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 2 147 483 647=231−12\,147\,483\,647 = 2^{31} - 1. NumPy arrays use fixed-width integers, so they wrap silently. (Python's own int never overflows, it just gets bigger.)

python · try it yourself
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]) ** 2 overflows here even though it would not on a 64-bit desktop. Pass dtype=np.int64 when 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) / 2 in 32-bit arithmetic can overflow for huge arrays. lo + (hi − lo) / 2 avoids 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 2n2^n 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
216=65 536 patternsunsigned: 0…216−1=65 535signed: −215…215−1=−32 768…32 767\begin{aligned} &2^{16} = 65\,536\ \text{patterns} \\ &\text{unsigned: } 0 \ldots 2^{16} - 1 = 65\,535 \\ &\text{signed: } -2^{15} \ldots 2^{15} - 1 = -32\,768 \ldots 32\,767 \end{aligned}

Exercise 2: Encode a negative number

Write −20 as an 8-bit two's complement pattern using "flip and add 1".

Answer

11101100

Solution
text
20   = 00010100
flip = 11101011
+1   = 11101100
check: −128 + 64 + 32 + 8 + 4 = −20 ✓
python · try it yourself
print(format(-20 & 0xFF, "08b"))
11101100

Exercise 3: Predict the wrap

In signed 8-bit arithmetic, what is 90+6090 + 60? And in unsigned 8-bit, what is 10−2010 - 20?

Answer

90+60=−10690 + 60 = -106 (signed); 10−20=24610 - 20 = 246 (unsigned).

Solution
90+60=150>127,so subtract 256: 150−256=−10610−20=−10<0,so add 256: −10+256=246\begin{aligned} 90 + 60 &= 150 > 127, && \text{so subtract 256: } 150 - 256 = -106 \\ 10 - 20 &= -10 < 0, && \text{so add 256: } -10 + 256 = 246 \end{aligned}

Every wrap moves the result by a multiple of 28=2562^8 = 256 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: 70 000−65 536=4 46470\,000 - 65\,536 = 4\,464.

python · try it yourself
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?

  1. 0 to 255
  2. −127 to 127
  3. −128 to 127
  4. −256 to 255

In 8-bit two's complement, what number is 11111111?

  1. 255
  2. −1
  3. −127
  4. −128

Which Python expression keeps only the lowest 8 bits of x, like an unsigned byte?

  1. x | 0xFF
  2. x >> 8
  3. x & 0xFF
  4. x ^ 0xFF