Adding Binary Numbers
An overflow occurs when a calculation produces a result that is larger than the maximum value that can be represented using the available bits. With 8 bits, the largest value you can store is 255, which is 11111111 in binary, so any total from 256 upwards cannot be held in 8 bits.
Suppose an 8-bit game score holds 186 points (10111010) and a player earns 103 more points (01100111). The true total is 289, so it needs nine bits.
| Column | 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 |
|---|---|---|---|---|---|---|---|---|
| First number | 1 | 0 | 1 | 1 | 1 | 0 | 1 | 0 |
| Second number | 0 | 1 | 1 | 0 | 0 | 1 | 1 | 1 |
| Carry in | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 |
| Result bit | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 |
Adding the columns produces a carry out of column 7, so the nine-bit total is 100100001. The bit in column 7 is the most significant bit, and the 1 that leaves it has nowhere to go, so it is lost. The 8 bits left behind are 00100001, which is 33, not 289. The stored result is wrong by 256, the value of the lost ninth bit.
Overflow happens when a carry leaves the most significant column. That occurs when both leftmost bits are 1, and also when a carry arrives into the leftmost column while one of the two leftmost bits is a 1, as in the score example, where column 7 works out as 1 + 0 + 1: a result bit of 0 with a carry out.
When you add two 8-bit numbers and the total is above 255, give the 8-bit binary result, show that the ninth bit has been produced and lost (for example, write it and cross it out), and state that an overflow has occurred. If a program does not deal with an overflow, it may carry on with the wrong value and produce incorrect output, or it may crash.
OCR GCSE Computer Science · Adding Binary Numbers