Computers are good at math. They’re well suited to something so strict, logical, and universal. But like many things, they are only as strong as their weakest link, and unfortunately for computers doing arithmetic, sometimes that weak link is how they handle numbers. That sounds pretty dire; you probably would not be able to do a whole lot of math without numbers. But if we can understand this weak point, we should be able to understand where the problem arises, and how we can work around the problem.

To start, you’re likely not going to have problems with something like 1+1=2, or 5*25=125. Relatively speaking, those are all rather small numbers, and unless you’ve directed your code to limit the size of numbers quite substantially, that math should always work out. But let’s do that! Let’s limit how large our numbers can be and then try some math with the largest numbers.

We’ll limit the the size of our numbers to eight bits, which will allow our largest number to be 255. Now, if we try doing 255+1, we’ll get zero. If we try 255+2, we’ll get 1. The number has reached its maximum size, is pushed past that limit, and it just loops back to the smallest value. Why does it do that? 255 seems somewhat arbitrary, but it should look more interesting in binary.

In binary, 255 is represented as eight, consecutive 1’s. And if we were limiting our numbers to eight bits, or that is eight 1’s or 0’s in binary, this would be the largest number we could store. Let’s look at 255+1 again, but with both 255 and 1 in binary.

We start off with 1+1=10. The zero gets placed, and the 1 carries over. For the next place we have 1+0=1, and then we add the 1 that was carried over for 1+0+1=10. The zero gets placed, and the 1 carries over. And then repeat several more times. If we allow a ninth bit, this will result in 100000000, or 256 in decimal. But if we don’t allow that ninth bit, the 1 gets cut off, and we only have 00000000, which, of course, is 0 in decimal. The comparison to odometer or a clock are very apt: numbers will continue to increase, and then once they go past their max, they drop back to the lowest value and start over. For the most part, this is how numbers are recorded in any computer.

This quality can lead to all sorts of problems or unpredictable behavior. And depending on the situation, it could also be a vulnerability in your security. Fortunately, most languages have protections against integer overflow, often in the form of some sort of clamp on the range. So, while you’re likely safe adding 9,007,199,254,740,991+1, you should check your language for how it handles extremely large and small numbers, and how it handles integer overflow.