See How Things Work

Overflow

Unit
Representing Information
Part
2. Numbers in a Computer
Lesson
2.3

Overflow happens when the exact result of an arithmetic operation lies outside the range that its fixed number of bits can store. This lesson shows what the machine keeps instead, proves how overflow is detected in unsigned and in two’s-complement addition, and describes what processors and programming languages do about it and real failures that overflow has caused.

When the result does not fit

An n-bit field holds at most 2ⁿ values (lesson 1.5), and only those of its range: 0 to 2ⁿ − 1 for unsigned integers (lesson 2.1), −2ⁿ⁻¹ to 2ⁿ⁻¹ − 1 in two’s complement (lesson 2.2). The exact sum of two values in the range need not be in it: 200 + 100 = 300 is not a byte.

Definition (Overflow).

An arithmetic operation on n-bit integers overflows when its exact result is not in the range of the type it is stored in. The C standard speaks of a result “not in the range of representable values for its type”;⁠[1] Intel’s manual, of a result too large a positive number or too small a negative number to fit in the destination.⁠[2]

An adder does not stop when the result does not fit. It writes its n bits as always, and the bits are the low n bits of the exact result. The Java language specification says this of integer addition: if it overflows, the result is the low-order bits of the mathematical sum.⁠[3] By Theorem 3 of lesson 2.1, the low n bits of a whole number are its remainder on division by 2ⁿ, so the stored value differs from the exact one by 2ⁿ, added or subtracted some number of times.

Definition (Wraparound).

Wraparound is the replacement of a value by the value in the range that differs from it by 2ⁿ, added or subtracted some number of times. There is exactly one such value, because the range consists of 2ⁿ consecutive integers. In practice: add or subtract 2ⁿ until the value is in the range. The C standard calls it the process by which a value is reduced modulo 2ᴺ, where N is the width of the type;⁠[4] “reducing modulo 2ᴺ” means exactly this adding or subtracting of 2ᴺ. Intel’s manual describes wraparound arithmetic in terms of the bits: the out-of-range result is truncated, and only its least significant bits are returned.⁠[5]

The circle of lesson 2.2 shows wraparound at a glance. Adding 1 moves one step clockwise. Going past the top, from 1111 to 0000, the unsigned value falls from 15 to 0; going past the bottom, from 0111 to 1000, the two’s-complement value falls from 7 to −8. How far the pointer moves depends on the reading. For unsigned integers, adding y moves y steps clockwise, less than a full turn; for two’s-complement integers, adding y ≥ 0 moves y steps clockwise and adding y < 0 moves |y| steps counterclockwise, at most half a turn. Then one addition overflows exactly when the pointer crosses the seam of its kind of number.

Unsigned overflow

Theorem 1 (unsigned addition).

Let x and y be n-bit unsigned integers, added in columns with the n bits kept.

  1. If x + y ≤ 2ⁿ − 1, the kept bits store x + y. Otherwise they store x + y − 2ⁿ.
  2. The addition overflows exactly when the carry out is 1.
  3. It overflows exactly when the kept result is smaller than x (and then it is also smaller than y).
Proof.

(1) and (2) are Theorem 4 of lesson 2.1: the sum always has n + 1 bits, the carry out is 1 exactly when x + y ≥ 2ⁿ, and then the n bits name x + y − 2ⁿ. (3) If the carry out is 1, the result is x + y − 2ⁿ ≤ x + (2ⁿ − 1) − 2ⁿ = x − 1, which is less than x; in the same way it is less than y. If the carry out is 0, the result is x + y, which is at least x.

Processors record the carry out: Intel’s carry flag is set by a carry or a borrow out of the most significant bit, and the manual calls it the flag that indicates an overflow condition for unsigned-integer arithmetic.⁠[6] A borrow out comes from subtraction: x − y with x < y has no unsigned result, and the n bits kept are 2ⁿ + x − y (lesson 2.1).

Caution.

Words differ between documents. The C standard says that a computation involving unsigned operands can never produce an overflow, because arithmetic for the unsigned type is performed modulo 2ᴺ:⁠[7] in C, the wrapped result is the defined result of unsigned arithmetic, so the standard does not call it an overflow. In this lesson, as in Intel’s manual, unsigned overflow means only that the exact result does not fit; the kept bits are the same either way.

Example (A counter of events).

An 8-bit unsigned counter stands at 250, and 10 more events arrive. What does it hold?

  1. 250 + 10 = 260 > 255: the exact result does not fit, an overflow.
  2. In bits: 11111010 + 00001010 = 100000100; the carry out is 1 and the kept bits are 00000100.
  3. By Theorem 1, they store 260 − 256 = 4.

Answer: 4. The overflow shows in the result itself: 4 is smaller than 250, which no correct sum of whole numbers could be.

Example (Sixteen bits in hexadecimal).

Add the 16-bit unsigned integers 0xFFF0 and 0x0020.

  1. Place 0: 0 + 0 = 0. Place 1: F + 2 = 17 = 16 + 1, write 1 and carry 1. Places 2 and 3: F + 1 = 16, write 0 and carry 1.
  2. The carry out is 1, so the kept 16 bits are 0x0010 = 16.
  3. Check: 65,520 + 32 = 65,552, and 65,552 − 65,536 = 16.

Answer: 0x0010 = 16, an overflow; the exact sum needs 17 bits.

Example (The edge case: counting down past zero).

An 8-bit unsigned counter holds 0 and is decreased by 1. What does it hold?

  1. 0 − 1 = −1 has no unsigned value: the subtraction must borrow out of position 7.
  2. The kept bits are 2⁸ + 0 − 1 = 255 = 11111111.

Answer: 255, the largest value. On the circle, one step counterclockwise from 0000 crosses the seam to 1111.

Example (A common mistake: testing the result against the largest value).

To detect overflow in 8-bit unsigned addition, someone adds x and y and then checks whether the result is greater than 255. Does the test work?

  1. The kept result is an 8-bit value, so it is never greater than 255: the test never fires.
  2. Tests that work: the carry out is 1; or, by Theorem 1 (3), the result is smaller than x.

Answer: no. After the bits are kept, the information that the sum was too large is in the carry out, not in the result.

Game

Around the circle

Round
1
Score
0
Streak
0

The pointer is at 1011, which stores −5 in two’s complement. Add 4. Tap the pattern that holds the 4-bit result, and say whether the result overflowed.

Two’s complement: the violet numbers inside the circle. Adding a positive number moves clockwise, a negative one counterclockwise.

0000010001200103001140100501016011070111−81000−71001−61010−51011−41100−31101−21110−11111

Overflow in two’s complement

Theorem 3 of lesson 2.2 showed that adding two’s-complement patterns as unsigned integers gives the right sum whenever the sum is in range. When it is not, the carry out is no guide: −1 + 1 = 0 is in range and produces a carry out (11111111 + 00000001 = 100000000), while 127 + 1 is out of range and produces none (01111111 + 00000001 = 10000000). The sign bits decide.

Theorem 2 (the sign rule).

Let x and y be n-bit two’s-complement integers, added as unsigned integers with n bits kept.

  1. If one of x and y is negative and the other is not, the sum never overflows.
  2. If both are at least 0, the sum overflows exactly when the kept sign bit is 1; the kept bits then store x + y − 2ⁿ.
  3. If both are negative, the sum overflows exactly when the kept sign bit is 0; the kept bits then store x + y + 2ⁿ.

In short: the addition overflows exactly when x and y have the same sign bit and the kept result has the other one.

Proof.

(1) If x < 0 ≤ y, then x ≤ x + y < y, so x + y lies between two values of the range, and is in it.

(2) If 0 ≤ x, y ≤ 2ⁿ⁻¹ − 1, the unsigned values of the patterns are x and y themselves, and x + y ≤ 2ⁿ − 2, so there is no carry out and the kept bits name x + y as an unsigned integer. If x + y ≤ 2ⁿ⁻¹ − 1, that is in range and its sign bit is 0. If x + y ≥ 2ⁿ⁻¹, it overflows, the sign bit of the kept bits is 1 (Proposition 1 of lesson 1.3), and by Theorem 1 of lesson 2.2 they store x + y − 2ⁿ.

(3) If −2ⁿ⁻¹ ≤ x, y ≤ −1, the unsigned values are x + 2ⁿ and y + 2ⁿ (lesson 2.2, Theorem 1), whose sum x + y + 2 × 2ⁿ is at least 2ⁿ: the carry out is 1, and the kept bits name w = x + y + 2ⁿ, between 0 and 2ⁿ − 2. If x + y ≥ −2ⁿ⁻¹ (no overflow), then w ≥ 2ⁿ⁻¹, its sign bit is 1, and it stores w − 2ⁿ = x + y. If x + y < −2ⁿ⁻¹ (overflow), then w < 2ⁿ⁻¹, its sign bit is 0, and it stores w = x + y + 2ⁿ.

The Java specification states the visible effect: if an integer addition overflows, the sign of the result is not the same as the sign of the mathematical sum.⁠[3] Intel’s processors keep a second flag for it, the overflow flag, which indicates an overflow condition for signed (two’s complement) arithmetic, beside the carry flag for unsigned arithmetic.⁠[2][6] One addition produces results for both readings: if the result is treated as an unsigned integer, the carry flag shows whether it is out of range, and if it is treated as a two’s-complement integer, the overflow flag does.⁠[8] The program, which knows how it reads the bits, decides which flag matters.

Sign bits of the two numbersSign bit keptOverflow?
0 and 00no
0 and 01yes: the exact sum is at least 2ⁿ⁻¹
1 and 11no
1 and 10yes: the exact sum is less than −2ⁿ⁻¹
0 and 10 or 1never
Table. When the sum of two n-bit two’s-complement integers overflows (Theorem 2). Only numbers of the same sign can overflow, and then the kept sign bit is wrong.
(a) no overflow+0011001000101unsigned: 3 + 2 = 5, fitstwo’s: 3 + 2 = 5, fits(b) unsigned overflow only+1110001110001unsigned: 14 + 3 = 17, kept 1two’s: −2 + 3 = 1, fits(c) two’s-complement overflow only+0110001101001unsigned: 6 + 3 = 9, fitstwo’s: 6 + 3 = 9, kept −7(d) both overflow+1001101010011unsigned: 9 + 10 = 19, kept 3two’s: −7 + (−6) = −13, kept 3
Figure. Four 4-bit sums, each read as unsigned integers and in two’s complement. (a) Neither reading overflows. (b) The carry out is 1, an unsigned overflow, but −2 + 3 = 1 is right. (c) No carry out, but two numbers with sign bit 0 give sign bit 1: 6 + 3 = 9 becomes −7. (d) Both: the carry out is 1, and two negative numbers give sign bit 0: −7 + (−6) = −13 becomes 3.
Example (Two positive numbers).

Add 100 and 50 in 8-bit two’s complement.

  1. 01100100 + 00110010 = 10010110, with no carry out.
  2. Both sign bits are 0 and the kept sign bit is 1: overflow, by Theorem 2 (2).
  3. The kept bits store 150 − 256 = −106.

Answer: overflow; the byte holds −106 instead of 150, which is larger than 127.

Example (A carry out without overflow).

Add −1 and 1 in 8-bit two’s complement.

  1. 11111111 + 00000001 = 100000000: the carry out is 1, and the kept bits are 00000000.
  2. The sign bits differ, so by Theorem 2 (1) there is no overflow.

Answer: 0, correct. Read as unsigned integers, the same sum, 255 + 1, does overflow: the bits are the same, the readings differ.

Example (The edge case: one step past the largest value).

Add 1 to 127 in 8-bit two’s complement.

  1. 01111111 + 00000001 = 10000000, no carry out.
  2. Both sign bits are 0, the kept sign bit is 1: overflow. The kept bits store 128 − 256 = −128.

Answer: −128. The largest value plus one becomes the smallest, as the circle’s seam between 0111 and 1000 shows for 4 bits.

Example (A subtraction that overflows).

Compute −100 − 50 in 8-bit two’s complement, as −100 + (−50).

  1. −100 = 10011100 and −50 = 11001110 (lesson 2.2).
  2. 10011100 + 11001110 = 101101010: carry out 1, kept bits 01101010.
  3. Both sign bits are 1 and the kept sign bit is 0: overflow, by Theorem 2 (3). The kept bits store −150 + 256 = 106.

Answer: overflow; the byte holds +106, because −150 is smaller than −128.

Game

Overflow detector

Round
1
Score
0
Streak
0

Add the two 8-bit patterns in columns and set the 8 bits that are kept. Then decide: does the sum overflow as unsigned integers, in two’s complement, both or neither?

01000011: unsigned 67, two’s complement 67

+ 10001101: unsigned 141, two’s complement −115

The 8 kept bits of the sum; a carry out of the leftmost column is dropped.

What processors and programs do

A processor adds the bits and sets its flags; what happens next depends on the instructions the program uses and on its language. Four common answers:

  • Wrap silently. In Java the integer operators do not indicate overflow or underflow in any way;⁠[9] the program receives the low-order bits.⁠[3]
  • Saturate. Some processor instructions replace an out-of-range result by the nearest end of the range. With Intel’s unsigned saturation arithmetic, a byte result that is too large comes out as 0xFF and one that is too small as 0x00.⁠[10] So 200 + 100 gives 255 there, not 44: still not 300, but the nearest value the byte can hold.
  • Leave it undefined. In C, a signed result outside the range of its type is an exceptional condition, and then the behavior is undefined;⁠[1] the standard defines undefined behavior as behavior for which it imposes no requirements.⁠[11] Unsigned arithmetic, by contrast, wraps modulo 2ᴺ.⁠[7]
  • Make the integers grow. In Python, integers have unlimited precision,⁠[12] so integer addition does not overflow at all.

Overflow can also happen without arithmetic, when a value is moved into a narrower type. Narrowing keeps the low bits (lesson 2.1, Theorem 3). The Java specification says that narrowing a signed integer discards all but the n lowest order bits, which can change the magnitude and even the sign of the value.⁠[13]

Example (Narrowing into 16 bits).

The numbers 40,000 and 70,000 are narrowed into 16-bit two’s complement. What do the 16 bits store?

  1. 40,000 < 65,536, so its low 16 bits are its 16-bit pattern 0x9C40. The sign bit is 1, so they store 40,000 − 65,536 = −25,536.
  2. 70,000 = 65,536 + 4,464, so its low 16 bits name 4,464 = 0x1170, with sign bit 0: they store 4,464.

Answer: −25,536 and 4,464. Both values are wrong, since 16-bit two’s complement ends at 32,767, and the first even changes sign.

A program can also test before it adds, using only numbers that are in range.

Proposition 3 (testing before adding).
  1. For n-bit unsigned integers, x + y overflows exactly when x > (2ⁿ − 1) − y.
  2. For n-bit two’s-complement integers with y ≥ 0, x + y overflows exactly when x > (2ⁿ⁻¹ − 1) − y.
  3. For n-bit two’s-complement integers with y < 0, x + y overflows exactly when x < −2ⁿ⁻¹ − y.

In each case the number on the right lies in the range, so computing it cannot overflow.

Proof.

(1) x + y > 2ⁿ − 1 exactly when x > 2ⁿ − 1 − y, by subtracting y from both sides; and 0 ≤ 2ⁿ − 1 − y ≤ 2ⁿ − 1. (2) For y ≥ 0 the sum cannot be too small, and x + y > 2ⁿ⁻¹ − 1 exactly when x > 2ⁿ⁻¹ − 1 − y, a number from 0 to 2ⁿ⁻¹ − 1. (3) For y < 0 the sum cannot be too large, and x + y < −2ⁿ⁻¹ exactly when x < −2ⁿ⁻¹ − y, a number from −2ⁿ⁻¹ + 1 to 0 (it is 0 when y = −2ⁿ⁻¹).

Example (Testing before adding).

In 8 bits, test 200 + 100 as unsigned integers, and 100 + 27 and 100 + 28 in two’s complement.

  1. Unsigned: 255 − 100 = 155, and 200 > 155, so 200 + 100 overflows.
  2. Two’s complement: 127 − 27 = 100, and 100 > 100 is false, so 100 + 27 = 127 fits.
  3. 127 − 28 = 99, and 100 > 99, so 100 + 28 overflows.

Answer: overflow, no overflow, overflow. The second sum lands exactly on the largest value, 127.

Overflow in the real world

Ariane 5, 1996. The first launch of the Ariane 5 launcher took place on 4 June 1996, from Kourou in French Guiana.⁠[14][15] The flight ended in failure: about 40 seconds after the flight sequence began, at an altitude of about 3,700 m, the launcher veered off its flight path, broke up and exploded.⁠[15] Its attitude and movements were measured by its inertial reference system, called SRI.⁠[16] The inquiry board traced the failure to a software exception in the SRI: a 64-bit floating-point number was being converted into a 16-bit signed integer, its value was larger than any 16-bit signed integer, and the conversion raised what the report calls an “Operand Error”.⁠[17]

The number was an internal result called BH, “Horizontal Bias”, related to the horizontal velocity that the platform sensed.⁠[18] BH came out much larger than expected because Ariane 5 follows a different early trajectory from Ariane 4’s, with considerably higher horizontal velocities.⁠[19] The backup SRI had already stopped one data cycle, 72 milliseconds, earlier, for the same reason.⁠[20] The flight computer then received a diagnostic bit pattern from the active SRI and treated it as flight data.⁠[21] The board named two “primary technical causes”: the Operand Error when BH was converted, and the lack of protection of this conversion, which made the SRI computer stop.⁠[22]

Caution.

Here the overflow did not wrap around silently. The conversion was not protected, and the system’s specification said that after any exception the failure was to be reported and the SRI processor shut down.⁠[23] Detecting overflow is not enough; a program must also decide what to do when it happens. How floating-point numbers such as the 64-bit value of BH are stored is the subject of this unit’s lesson “Floating-point numbers”.

Example (What a 16-bit signed integer can hold).

Which values could the conversion of BH store without error, if the 16-bit signed integer is stored in two’s complement?

  1. In two’s complement, the usual way of storing signed integers (lesson 2.2), 16 bits hold −2¹⁵ to 2¹⁵ − 1.
  2. 2¹⁵ = 32,768, so the range is −32,768 to 32,767.

Answer: the whole numbers from −32,768 to 32,767, 65,536 values; a number above 32,767 or below −32,768 has no 16-bit signed pattern. The report does not give the value BH had in flight, only that it was greater than a 16-bit signed integer can hold.

The year 2038. On POSIX systems the type time_t counts the seconds elapsed since the POSIX Epoch, 1 January 1970 at 00:00:00 UTC.⁠[24] Such time values exceed the largest value of a signed 32-bit integer in January 2038.⁠[25] The GNU documentation puts it exactly: programs that use a 32-bit signed time_t cannot represent timestamps on or after 2038-01-19 03:14:08 UTC, and unpredictable behavior will likely occur in them in the year 2038;⁠[26] a 32-bit time_t stops working in the year 2038.⁠[27] The remedy is width: POSIX.1-2024 requires time_t to be at least 64 bits wide,⁠[28] and in the GNU C Library time_t is 64 bits wide on all its platforms, except a few older ones where it is 32 bits unless a program asks for 64.⁠[29]

7FFFFFFF01110x7FFFFFFF = 2,147,483,647 = 2³¹ − 1,the largest 32-bit two’s-complement value8000000010000x80000000: unsigned 2,147,483,648, but intwo’s complement −2,147,483,648 = −2³¹0x0x+ 1 second
Figure. A 32-bit two’s-complement count of seconds at its largest value, 0x7FFFFFFF, and one second later. Adding 1 in columns carries into the sign bit (violet nibble, 0111 becoming 1000), and the kept 32 bits, read in two’s complement, store the most negative value.
Example (Checking the date of 2038).

Show that the largest 32-bit two’s-complement value, counted in seconds from midnight, ends at 03:14:07 on its last day.

  1. The largest value is 2³¹ − 1 = 2,147,483,647 seconds. A day has 24 × 60 × 60 = 86,400 seconds.
  2. 2,147,483,647 = 24,855 × 86,400 + 11,647: 24,855 whole days and 11,647 seconds.
  3. 11,647 = 3 × 3,600 + 14 × 60 + 7: 3 hours, 14 minutes and 7 seconds.

Answer: the last second that fits is 03:14:07 on the day 24,855 days after 1 January 1970, a little over 68 years of 365 days (68 × 365 = 24,820). One second later, at 03:14:08, the count needs 2³¹, which does not fit. If the addition wraps around, the count becomes −2³¹, a moment about 68 years before 1970. This agrees with the GNU documentation’s first unrepresentable moment, 2038-01-19 03:14:08 UTC.

An aircraft counter, 2015. In 2015 the U.S. Federal Aviation Administration issued an airworthiness directive after determining that a Boeing 787 airplane powered continuously for 248 days could lose all alternating current (AC) electrical power, because a software counter in its generator control units would overflow after 248 days of continuous power.⁠[30] The directive required a repetitive maintenance task, the deactivation of the electrical power, on these airplanes.⁠[31] It does not say what the counter counted or how many bits it had.

Security. Integer overflow is a recognized class of software weakness: the Common Weakness Enumeration lists “Integer Overflow or Wraparound”, a calculation that can overflow or wrap around when the program assumes that the result will always be larger than the original value.⁠[32] A computer science textbook names the root of the trouble: programmers tend to think of integers as mathematical integers.⁠[33]

Looking ahead.

Overflow also exists for floating-point numbers, with different rules; it is treated in “Floating-point numbers” and “Rounding error in floating point”. Python’s own integers, and the fixed-width integers of the numerical libraries used later in the course, are met again in the units Programming Fundamentals and Numerical Computing.

Exercises

Exercise .

Add 180 and 90 as 8-bit unsigned integers. Does the sum overflow? What do the kept bits store?

▸ Show solution

180 = 10110100 and 90 = 01011010. 180 + 90 = 270 > 255: overflow, with carry out 1.

The kept bits are 270 − 256 = 14 = 00001110; and 14 < 180, as Theorem 1 (3) predicts.

Exercise .

In 8-bit two’s complement, which of these sums overflow, and what is stored: (a) 90 + 40, (b) −90 + 40, (c) −90 + (−40), (d) −128 + (−1)?

▸ Show solution

(a) 90 + 40 = 130 > 127: overflow; both sign bits 0, kept sign bit 1; stored 130 − 256 = −126.

(b) −90 + 40 = −50: the signs differ, no overflow.

(c) −90 + (−40) = −130 < −128: overflow; stored −130 + 256 = 126.

(d) −128 + (−1) = −129: overflow; stored −129 + 256 = 127.

Exercise .

Describe all 4-bit sums that overflow both as unsigned integers and in two’s complement. How many ordered pairs of 4-bit patterns give such a sum?

▸ Show solution

By Theorem 2, a two’s-complement overflow needs two numbers with the same sign bit. If both sign bits are 0, the unsigned values are at most 7 and their sum at most 14, so there is no unsigned overflow. If both sign bits are 1, the unsigned values are at least 8, their sum at least 16, and the carry out is always 1: an unsigned overflow every time. So a 4-bit sum overflows in both readings exactly when both numbers are negative and their exact sum is less than −8.

Count the ordered pairs (x, y) of negative values with x + y ≥ −8: for x = −1 there are 7 values of y (−7 to −1), for x = −2 there are 6, and so on down to 1 for x = −7 and 0 for x = −8: 7 + 6 + 5 + 4 + 3 + 2 + 1 = 28. Of the 8 × 8 = 64 pairs of negative values, 64 − 28 = 36 overflow both ways.

Exercise .

Prove that the addition of two n-bit two’s-complement integers overflows exactly when the carry into the leftmost column differs from the carry out of it.

▸ Show solution

Let a and b be the sign bits and c the carry into the leftmost column. The column holds t = a + b + c; it writes the bit t − 2 if t ≥ 2 and t otherwise, and carries out 1 exactly when t ≥ 2.

  • a = b = 0: t = c, so the kept sign bit is c and the carry out 0. By Theorem 2, overflow ⇔ kept sign bit 1 ⇔ c = 1 ⇔ c ≠ carry out.
  • a = b = 1: t = 2 + c, so the kept sign bit is c and the carry out 1. Overflow ⇔ kept sign bit 0 ⇔ c = 0 ⇔ c ≠ carry out.
  • a ≠ b: t = 1 + c, so the carry out equals c. There is never an overflow, and never a difference between c and the carry out.

So a two’s-complement addition overflows exactly when the carry into the sign position differs from the carry out of it.

Exercise .

A counter of hundredths of a second is kept as a 32-bit two’s-complement integer, starting from 0. After how many days does it overflow?

▸ Show solution

The largest value is 2³¹ − 1 = 2,147,483,647 hundredths of a second, which is 21,474,836.47 seconds. Divided by 86,400 seconds per day this is about 248.55 days: 248 days and about 13 hours.

This is only arithmetic about such a counter. The FAA directive gives 248 days for the 787’s counter but does not say how that counter worked, so the calculation does not show what its cause was.

Exercise .

Compute 5 − 9 in 8-bit unsigned integers. What is stored, and how can a program detect the problem before subtracting?

▸ Show solution

5 − 9 = −4 has no unsigned value: the subtraction borrows out, and the kept bits are 256 + 5 − 9 = 252 = 11111100.

A borrow out happens exactly when x < y, so testing x < y before subtracting detects it, and the test itself involves no arithmetic that could overflow.

Exercise .

Which 32-bit two’s-complement values overflow when negated, and what does the negation return? Explain with lesson 2.2.

▸ Show solution

The exact result of −x is outside the range only for x = −2ⁿ⁻¹ (lesson 2.2, Theorem 2). For 32 bits, −(−2,147,483,648) = 2,147,483,648 is one more than the largest value 2,147,483,647, so the negation overflows and, by Theorem 2 of lesson 2.2, gives back −2,147,483,648. Every other 32-bit value negates without overflow.

Summary

  1. An operation overflows when its exact result is outside the range of its n-bit type. The adder still keeps n bits: the exact result reduced modulo 2ⁿ, that is, with 2ⁿ added or subtracted until it is in range (wraparound).
  2. Unsigned addition overflows exactly when the carry out is 1, and then the kept result is the sum minus 2ⁿ, smaller than either number. Subtraction of a larger number borrows out.
  3. Two’s-complement addition overflows exactly when both numbers have the same sign bit and the kept result has the other; the carry out says nothing about it. Processors set a carry flag and an overflow flag for the two readings.
  4. Languages and instructions differ: Java wraps silently, saturating instructions stop at the ends of the range, C leaves signed overflow undefined and wraps unsigned arithmetic, Python’s integers grow. Narrowing keeps the low bits and can change the sign. Testing x > max − y before adding avoids overflow.
  5. Overflow has real consequences: the Ariane 5 failure of 1996 began with a 64-bit value too large for a 16-bit signed integer, and 32-bit signed counts of seconds since 1970 run out in January 2038.

Sources

  1. 1.
    ISO/IEC JTC 1/SC 22/WG 14, “N3220: working draft of ISO/IEC 9899:2024 (C23), the C programming language standard. A free draft that the C committee lists as similar to the published standard, not the ISO text itself”, open-std.org, the site of the ISO C standards committee (22 February 2024).
    Section “6.5.1, “General” (in 6.5, “Expressions”), paragraph 5 (p. 72)”. open-std.org/jtc1/sc22/wg14/www/docs/n3220.pdf · open at the quoted passage.
    “If an exceptional condition occurs during the evaluation of an expression (that is, if the result is not mathematically defined or not in the range of representable values for its type), the behavior is undefined.”
    Used for: a result not in the range of representable values for its type is an exceptional condition in C, and the behavior is then undefined.
  2. 2.
    Intel Corporation, “Intel 64 and IA-32 Architectures Software Developer’s Manual, Volume 1: Basic Architecture (order number 253665-084US)”, Intel (June 2024).
    Section “3.4.3.1, “Status Flags” (p. 3-16)”. cdrdv2-public.intel.com/825744/253665-sdm-vol-1.pdf · open at the quoted passage.
    “Overflow flag — Set if the integer result is too large a positive number or too small a negative number (excluding the sign-bit) to fit in the destination operand; cleared otherwise. This flag indicates an overflow condition for signed-integer (two’s complement) arithmetic.”
    Used for: Intel’s overflow flag: the result is too large a positive or too small a negative number to fit in the destination; it indicates overflow for signed (two’s complement) arithmetic.
  3. 3.
    James Gosling and others, “The Java Language Specification, Java SE 25 Edition, Chapter 15: Expressions”, Oracle (2025).
    Section “15.18.2, “Additive Operators (+ and -) for Numeric Types””. docs.oracle.com/javase/specs/jls/se25/html/jls-15.html · open at the quoted passage.
    “If an integer addition overflows, then the result is the low-order bits of the mathematical sum as represented in some sufficiently large two's-complement format. If overflow occurs, then the sign of the result is not the same as the sign of the mathematical sum of the two operand values.”
    Used for: an overflowing integer addition keeps the low-order bits of the exact sum, and then the sign of the result differs from the sign of the exact sum.
  4. 4.
    ISO/IEC JTC 1/SC 22/WG 14, “N3220: working draft of ISO/IEC 9899:2024 (C23), the C programming language standard. A free draft that the C committee lists as similar to the published standard, not the ISO text itself”, open-std.org, the site of the ISO C standards committee (22 February 2024).
    Section “3.28, “wraparound” (the term on p. 7, its definition on p. 8)”. open-std.org/jtc1/sc22/wg14/www/docs/n3220.pdf · open at the quoted passage.
    “the process by which a value is reduced modulo 2ᴺ, where N is the width of the resulting type”
    Used for: wraparound: a value reduced modulo 2ᴺ, where N is the width of the type.
  5. 5.
    Intel Corporation, “Intel 64 and IA-32 Architectures Software Developer’s Manual, Volume 1: Basic Architecture (order number 253665-084US)”, Intel (June 2024).
    Section “9.3, “Saturation and Wraparound Modes” (p. 9-4)”. cdrdv2-public.intel.com/825744/253665-sdm-vol-1.pdf · open at the quoted passage.
    “Wraparound arithmetic — With wraparound arithmetic, a true out-of-range result is truncated (that is, the carry or overflow bit is ignored and only the least significant bits of the result are returned to the destination).”
    Used for: Intel’s wraparound arithmetic: an out-of-range result is truncated, and only its least significant bits are returned.
  6. 6.
    Intel Corporation, “Intel 64 and IA-32 Architectures Software Developer’s Manual, Volume 1: Basic Architecture (order number 253665-084US)”, Intel (June 2024).
    Section “3.4.3.1, “Status Flags” (p. 3-16)”. cdrdv2-public.intel.com/825744/253665-sdm-vol-1.pdf · open at the quoted passage.
    “Carry flag — Set if an arithmetic operation generates a carry or a borrow out of the most-significant bit of the result; cleared otherwise. This flag indicates an overflow condition for unsigned-integer arithmetic.”
    Used for: Intel’s carry flag: set by a carry or borrow out of the most significant bit; it indicates overflow for unsigned arithmetic.
  7. 7.
    ISO/IEC JTC 1/SC 22/WG 14, “N3220: working draft of ISO/IEC 9899:2024 (C23), the C programming language standard. A free draft that the C committee lists as similar to the published standard, not the ISO text itself”, open-std.org, the site of the ISO C standards committee (22 February 2024).
    Section “6.2.5, “Types”, paragraph 11 (p. 39)”. open-std.org/jtc1/sc22/wg14/www/docs/n3220.pdf · open at the quoted passage.
    “A computation involving unsigned operands can never produce an overflow, because arithmetic for the unsigned type is performed modulo 2ᴺ.”
    Used for: in C, unsigned arithmetic is performed modulo 2ᴺ and is said never to overflow.
  8. 8.
    Intel Corporation, “Intel 64 and IA-32 Architectures Software Developer’s Manual, Volume 1: Basic Architecture (order number 253665-084US)”, Intel (June 2024).
    Section “3.4.3.1, “Status Flags” (p. 3-17)”. cdrdv2-public.intel.com/825744/253665-sdm-vol-1.pdf · open at the quoted passage.
    “If the result of an arithmetic operation is treated as an unsigned integer, the CF flag indicates an out-of-range condition (carry or a borrow); if treated as a signed integer (two’s complement number), the OF flag indicates a carry or borrow”
    Used for: one arithmetic result can be read both ways: read as unsigned, the carry flag shows that it is out of range; read as two’s complement, the overflow flag does.
  9. 9.
    James Gosling and others, “The Java Language Specification, Java SE 25 Edition, Chapter 4: Types, Values, and Variables”, Oracle (2025).
    “The integer operators do not indicate overflow or underflow in any way.”
    Used for: Java’s integer operators do not indicate overflow in any way.
  10. 10.
    Intel Corporation, “Intel 64 and IA-32 Architectures Software Developer’s Manual, Volume 1: Basic Architecture (order number 253665-084US)”, Intel (June 2024).
    Section “9.3, “Saturation and Wraparound Modes” (p. 9-4)”. cdrdv2-public.intel.com/825744/253665-sdm-vol-1.pdf · open at the quoted passage.
    “With unsigned saturation arithmetic, out-of-range results are limited to the representable range of unsigned integers for the integer size. So, positive overflow when operating on unsigned byte integers results in FFH being returned and negative overflow results in 00H being returned.”
    Used for: Intel’s unsigned saturation arithmetic: a byte result that is too large comes out as 0xFF (FFH), one that is too small as 0x00 (00H).
  11. 11.
    ISO/IEC JTC 1/SC 22/WG 14, “N3220: working draft of ISO/IEC 9899:2024 (C23), the C programming language standard. A free draft that the C committee lists as similar to the published standard, not the ISO text itself”, open-std.org, the site of the ISO C standards committee (22 February 2024).
    Section “3.5.3, “undefined behavior” (p. 4)”. open-std.org/jtc1/sc22/wg14/www/docs/n3220.pdf · open at the quoted passage.
    “behavior, upon use of a nonportable or erroneous program construct or of erroneous data, for which this document imposes no requirements”
    Used for: the C standard defines undefined behavior as behavior for which it imposes no requirements.
  12. 12.
    “Built-in Types: Numeric Types — int, float, complex”, Python 3 documentation, Python Software Foundation.
    Section “Numeric Types — int, float, complex”. docs.python.org/3/library/stdtypes.html · open at the quoted passage.
    “Integers have unlimited precision.”
    Used for: Python’s integers have unlimited precision, so integer addition does not overflow.
  13. 13.
    James Gosling and others, “The Java Language Specification, Java SE 25 Edition, Chapter 5: Conversions and Contexts”, Oracle (2025).
    Section “5.1.3, “Narrowing Primitive Conversion””. docs.oracle.com/javase/specs/jls/se25/html/jls-5.html · open at the quoted passage.
    “A narrowing conversion of a signed integer to an integral type T simply discards all but the n lowest order bits, where n is the number of bits used to represent type T. In addition to a possible loss of information about the magnitude of the numeric value, this may cause the sign of the resulting value to differ from the sign of the input value.”
    Used for: narrowing a signed integer keeps the n lowest bits, which can change its magnitude and its sign.
  14. 14.
    “N° 20-1996: Flight 501 failure – first information”, European Space Agency, Media advisories (6 June 1996).
    “The first Ariane-5 launch took place on Tuesday, 4 June 1996, from the Guiana Space Centre, Europe's Spaceport, at Kourou in French Guiana.”
    Used for: the first Ariane 5 launch took place on 4 June 1996, from Kourou in French Guiana (ESA’s statement two days after the launch).
  15. 15.
    Inquiry Board (J. L. Lions, chairman), “ARIANE 5 Flight 501 Failure: Report by the Inquiry Board (Paris, 19 July 1996)”, European Space Agency (1996).
    “On 4 June 1996, the maiden flight of the Ariane 5 launcher ended in a failure. Only about 40 seconds after initiation of the flight sequence, at an altitude of about 3700 m, the launcher veered off its flight path, broke up and exploded.”
    Used for: the first flight of Ariane 5, on 4 June 1996, ended in failure: about 40 seconds after the flight sequence began, at about 3,700 m, the launcher veered off its path, broke up and exploded.
  16. 16.
    Inquiry Board (J. L. Lions, chairman), “ARIANE 5 Flight 501 Failure: Report by the Inquiry Board (Paris, 19 July 1996)”, European Space Agency (1996).
    Section 2.1, “Chain of technical events”, p. 3. esamultimedia.esa.int/docs/esa-x-1819eng.pdf · open at the quoted passage.
    “The attitude of the launcher and its movements in space are measured by an Inertial Reference System (SRI).”
    Used for: the attitude and movements of the launcher were measured by its inertial reference system, SRI.
  17. 17.
    Inquiry Board (J. L. Lions, chairman), “ARIANE 5 Flight 501 Failure: Report by the Inquiry Board (Paris, 19 July 1996)”, European Space Agency (1996).
    Section 2.1, “Chain of technical events”, p. 4. esamultimedia.esa.int/docs/esa-x-1819eng.pdf · open at the quoted passage.
    “The internal SRI software exception was caused during execution of a data conversion from 64-bit floating point to 16-bit signed integer value. The floating point number which was converted had a value greater than what could be represented by a 16-bit signed integer. This resulted in an Operand Error.”
    Used for: the SRI software exception was caused by converting a 64-bit floating-point value to a 16-bit signed integer; the value was greater than a 16-bit signed integer can represent, which resulted in an Operand Error.
  18. 18.
    Inquiry Board (J. L. Lions, chairman), “ARIANE 5 Flight 501 Failure: Report by the Inquiry Board (Paris, 19 July 1996)”, European Space Agency (1996).
    Section 2.1, “Chain of technical events”, p. 4. esamultimedia.esa.int/docs/esa-x-1819eng.pdf · open at the quoted passage.
    “The Operand Error occurred due to an unexpected high value of an internal alignment function result called BH, Horizontal Bias, related to the horizontal velocity sensed by the platform.”
    Used for: the value was an internal result called BH, Horizontal Bias, related to the horizontal velocity sensed by the platform.
  19. 19.
    Inquiry Board (J. L. Lions, chairman), “ARIANE 5 Flight 501 Failure: Report by the Inquiry Board (Paris, 19 July 1996)”, European Space Agency (1996).
    Section 2.1, “Chain of technical events”, p. 4. esamultimedia.esa.int/docs/esa-x-1819eng.pdf · open at the quoted passage.
    “The value of BH was much higher than expected because the early part of the trajectory of Ariane 5 differs from that of Ariane 4 and results in considerably higher horizontal velocity values.”
    Used for: BH was much higher than expected because Ariane 5’s early trajectory differs from Ariane 4’s and gives considerably higher horizontal velocities.
  20. 20.
    Inquiry Board (J. L. Lions, chairman), “ARIANE 5 Flight 501 Failure: Report by the Inquiry Board (Paris, 19 July 1996)”, European Space Agency (1996).
    Section 2.1, “Chain of technical events”, p. 3–4. esamultimedia.esa.int/docs/esa-x-1819eng.pdf · open at the quoted passage.
    “The OBC could not switch to the back-up SRI 1 because that unit had already ceased to function during the previous data cycle (72 milliseconds period) for the same reason as SRI 2.”
    Used for: the backup SRI had stopped one data cycle (72 milliseconds) earlier, for the same reason.
  21. 21.
    Inquiry Board (J. L. Lions, chairman), “ARIANE 5 Flight 501 Failure: Report by the Inquiry Board (Paris, 19 July 1996)”, European Space Agency (1996).
    Section 2.1, “Chain of technical events”, p. 3. esamultimedia.esa.int/docs/esa-x-1819eng.pdf · open at the quoted passage.
    “Part of these data at that time did not contain proper flight data, but showed a diagnostic bit pattern of the computer of the SRI 2, which was interpreted as flight data.”
    Used for: the flight computer received a diagnostic bit pattern from the active SRI and treated it as flight data.
  22. 22.
    Inquiry Board (J. L. Lions, chairman), “ARIANE 5 Flight 501 Failure: Report by the Inquiry Board (Paris, 19 July 1996)”, European Space Agency (1996).
    Section 2.2, “Comments on the failure scenario”, p. 4. esamultimedia.esa.int/docs/esa-x-1819eng.pdf · open at the quoted passage.
    “In the failure scenario, the primary technical causes are the Operand Error when converting the horizontal bias variable BH, and the lack of protection of this conversion which caused the SRI computer to stop.”
    Used for: the primary technical causes: the Operand Error when converting BH, and the lack of protection of this conversion, which caused the SRI computer to stop.
  23. 23.
    Inquiry Board (J. L. Lions, chairman), “ARIANE 5 Flight 501 Failure: Report by the Inquiry Board (Paris, 19 July 1996)”, European Space Agency (1996).
    Section 2.2, “Comments on the failure scenario”, p. 5. esamultimedia.esa.int/docs/esa-x-1819eng.pdf · open at the quoted passage.
    “In the event of any kind of exception, the system specification stated that: the failure should be indicated on the databus, the failure context should be stored in an EEPROM memory (which was recovered and read out for Ariane 501), and finally, the SRI processor should be shut down.”
    Used for: after any exception, the system specification required the failure to be reported and the SRI processor to be shut down.
  24. 24.
    “The GNU C Library Reference Manual, 22.4.1 “Time Types””, GNU Project, Free Software Foundation (sourceware.org).
    “On POSIX-conformant systems, time_t is an integer type and its values represent the number of seconds elapsed since the POSIX Epoch, which is January 1, 1970, at 00:00:00 Coordinated Universal Time (UTC).”
    Used for: time_t counts the seconds elapsed since the POSIX Epoch, 1 January 1970 at 00:00:00 UTC.
  25. 25.
    “Year 2038 considerations for uses of krb5_timestamp”, MIT Kerberos Documentation (krb5-1.22), Massachusetts Institute of Technology.
    “POSIX time values, which measure the number of seconds since January 1 1970, will exceed the maximum value representable in a signed 32-bit integer in January 2038.”
    Used for: POSIX time values exceed the largest value of a signed 32-bit integer in January 2038 (a second, independent source).
  26. 26.
    “GNU Gnulib manual, 15.5 “Avoiding the year 2038 problem””, GNU Project, Free Software Foundation.
    “The year 2038 problem denotes unpredictable behaviour that will likely occur in the year 2038, for programs that use a 32-bit signed integer ‘time_t’ type that cannot represent timestamps on or after 2038-01-19 03:14:08 UTC.”
    Used for: programs with a 32-bit signed time_t cannot represent timestamps on or after 2038-01-19 03:14:08 UTC, and unpredictable behavior will likely occur in them in the year 2038.
  27. 27.
    “The GNU C Library Reference Manual, 2.2.1 “Feature Test Macros””, GNU Project, Free Software Foundation (sourceware.org).
    “This is not recommended, as 32-bit time_t stops working in the year 2038.”
    Used for: a 32-bit time_t stops working in the year 2038.
  28. 28.
    “<sys/types.h>: data types”, The Open Group Base Specifications Issue 8 (IEEE Std 1003.1-2024, POSIX) (2024).
    “time_t shall be an integer type with a width (see <stdint.h>) of at least 64 bits.”
    Used for: POSIX.1-2024 requires time_t to be at least 64 bits wide.
  29. 29.
    “The GNU C Library Reference Manual, 22.4.1 “Time Types””, GNU Project, Free Software Foundation (sourceware.org).
    “Currently the time_t type is 64 bits wide on all platforms supported by the GNU C Library, except that it is 32 bits wide on a few older platforms unless you define _TIME_BITS to 64.”
    Used for: in the GNU C Library time_t is 64 bits wide on all platforms, except a few older ones where it is 32 bits unless a program asks for 64.
  30. 30.
    Federal Aviation Administration, U.S. Department of Transportation, “Airworthiness Directives; The Boeing Company Airplanes (AD 2015-09-07), 80 FR 24789”, Federal Register (1 May 2015).
    “This AD was prompted by the determination that a Model 787 airplane that has been powered continuously for 248 days can lose all alternating current (AC) electrical power due to the generator control units (GCUs) simultaneously going into failsafe mode. This condition is caused by a software counter internal to the GCUs that will overflow after 248 days of continuous power.”
    Used for: a Boeing 787 powered continuously for 248 days could lose all AC electrical power, because a software counter in its generator control units would overflow after 248 days of continuous power.
  31. 31.
    Federal Aviation Administration, U.S. Department of Transportation, “Airworthiness Directives; The Boeing Company Airplanes (AD 2015-09-07), 80 FR 24789”, Federal Register (1 May 2015).
    “This AD requires a repetitive maintenance task for electrical power deactivation on Model 787 airplanes.”
    Used for: the directive required a repeated maintenance task for electrical power deactivation.
  32. 32.
    “CWE-190: Integer Overflow or Wraparound”, Common Weakness Enumeration, The MITRE Corporation.
    “The product performs a calculation that can produce an integer overflow or wraparound when the logic assumes that the resulting value will always be larger than the original value.”
    Used for: integer overflow or wraparound is listed as a software weakness: a calculation that can overflow or wrap around when the logic assumes the result will always be larger than the original value.
  33. 33.
    Jean-Claude Franchitti and others, Introduction to Computer Science (web PDF of April 20, 2026, OpenStax, Rice University, 2024).
    Chapter 14, “Cyber Resources Qualities and Cyber Computing Governance”, section 14.2, “Cybersecurity Deep Dive” (“Integer Overflow Attacks and Defenses”), p. 861 (the whole topic: pp. 861).
    “Programmers have a tendency to think about integers as mathematical integers.”
    Used for: programmers tend to think of integers as mathematical integers.