Integer Overflow

alpharithms fallback 1

Integer overflow occurs when an arithmetic operation results in a value that can’t be represented by a finite number of digits. This includes values higher than the maximum and lower than the minimum. A common example is the mileage gauge on a car – after mile 999,999 it carries over to 000,000 representing an incorrect value.

In computer science, this phenomenon is often referred to as binary overflow because it commonly occurs when adding binary numbers. Depending on which language one is programming in, integer overflow may be handled in different ways.

Wrap Around

The C17 ISO/IEC 9899:2018 for C dictates that, for unsigned integer values, overflow is ignored and the value is returned as the value modulus the maximum. For example, in a 4-bit unsigned range 0-15, a value of 16 would be “wrapped around” by calculating 16 % 15 = 1.

Generally speaking, the maximum values for computing are restricted by the bit size of CPU registers (a.k.a. register width). For example, a 4-bit CPU would provide a range of 0-15 integers reflective of the above example. However, an 8-bit CPU would provide a maximum value of 65,535—considerably more. Below is a table summarizing the number of available values given a specific CPU registry size :

max_size max_value
4 bits 24 – 1 = 15
8 bits 28 – 1 = 255
16 bits 216 – 1 = 65535
32 bits 232 – 1 = 4,294,967,295
64 bits 264 – 1 = 18,446,744,073,709,551,615

Detecting Overflow

Overflow can be predicted given knowledge of certain conditions such as arithmetic operation, operand sign, and register size. For example, knowing that adding two numbers that are >= the maximum size / 2 can predict overflow.

What if you were to start adding negatives? What about subtracting operands of the same sign? A series of conditions can be generalized such that overflow can be predicted given ceratin relationships of operands, the operation being performed, and the resulting value. These conditions (for addition and subtraction) are as follows:

Operation A B Overflow Condition
A + B A >= 0 B >= 0 result < 0
A + B A < 0 B < 0 result >= 0
A – B A >= 0 B < 0 result < 0
A – B A < 0 B >= 0 result >= 0

In the C language, it’s up to the programmer whether or not to check for overflow. In other languages, such as ADA, it’s a requirement for application logic to handle overflow (R).

Note: This article is about integer overflow that can occur in the binary representation of numbers. For information on the CSS property overflow-integer reference the Mozilla MDN article here.

Zαck West
BSc Graphic Comm. NSCU, BSc CS Candidate WCU. Life-long learner and entrepreneur specializing in design, digital marketing, and web app development. Fascinated by natural systems, concurrency, and the nature of consciousness.