Integer Overflow

When you create an integer variable, your computer allocate 64 bits for storing it. What if your n…

When you create an integer variable, your computer allocates a fixed number of bits for storing it. Most modern computers use 32 or 64 bits. But some numbers are so big they don't fit even in 64 bits, like sextillion (a billion trillon), which is 70 digits in binary.

Sometimes we might have a number that does fit in 32 or 64 bits, but if we add to it (or multiply it by something, or do another operation) the result might not fit in the original 32 or 64 bits. This is called an integer overflow .

For example, let's say we have just 2 bits to store integers with. So we can only hold the unsigned (non-negative) integers 0-3 in binary:

00 (0)
01 (1)
10 (2)
11 (3)

What happens next depends on the language:

In languages where integer overflow can occur, you can reduce its likelihood by using larger integer types, like C's long long int or Java's long . If you need to store something even bigger, there are libraries built to handle arbitrary large numbers.

In some languages, you can also take advantage of overflow – checking features provided by the compiler or interpreter.

Date: 2020-01-31 Fri 16:11

Author: Jack Liu

Created: 2020-02-08 Sat 21:26