# Integer Overflow

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.