SDD Topic has been refreshed!
When learning binary back in S3 you were told there was less rules of arithmetic. There are only 4 rules of arithmetic when adding binary numbers. For this example we will assume that we are dealing with unsigned ( positive numbers).
These 4 rules are shown below:
The 4 rules of binary addition
As 1 plus 1 equals 2 which in binary is 10. The 1 is carried over (shown as the smaller red digit)
Again working with unsigned positive numbers we need to consider if there is a carry out from the result of an addition. An example is shown below:
The addition above is 17 + 91 = 0110 1100. The carry flag would be set to 0 (more on the carry flag here)
An example with a carry is shown below:
The addition above is 145 + 219 = 1 0110 1100. The carry would be set to 1 in this case
An overflow error occurs when the computer attempts to handle a number that is too large for it.
Every computer has a range of values that it can represent.
If during execution of a program it arrives at a number outside this range, it will experience an overflow error.
In computer processors, the overflow flag is usually a single bit register used to indicate when an arithmetic overflow has occurred in an operation.
Just a reminder that we can use two’s complement to perform addition/subtraction. An example is shown below
If 2 Two's Complement numbers are added and they both have the same sign, both positive or both negative then an overflow occurs if and only if the result (MSB) has the opposite sign.
It is important to remember that the overflow flag is only used when performing signed (two’s complement) arithmetic
Consider the value that would be stored in the register as a result of adding the 8-bit two’s complement numbers
0111 1111 (127) + 0000 0111 (7) which should give us 134.
As we are dealing with signed numbers the sign bit being 1 represents a negative number. If we convert to decimal the answer is -122 which is definitely not correct.
The result of the calculation is too large to fit into the required 8 bits available in the register.
You will notice that the sign bit of the result is 1 (negative). Given that we have added two positive numbers there is no valid result that could create a positive result so we can establish that an overflow has occurred.