| Arithmetic: overflow | ||||||||||||||
| So far, we have always assumed that we have enough bits to represent a value. | ||||||||||||||
| However, a computer must work with a finite number of bits. | ||||||||||||||
| What happens if the result doesn't fit in the available bits? | ||||||||||||||
| This is called overflow. | ||||||||||||||
| Overflow occurs when the result of an operation is greater than the max possible value | ||||||||||||||
| or less than the min value. | ||||||||||||||
| In UB: | ||||||||||||||
| carry | 1 | 1 | 1 | 1 | ||||||||||
| 1 | 0 | 1 | 1 | 11 | ||||||||||
| 0 | 1 | 1 | 1 | 7 | ||||||||||
| result | 0 | 0 | 1 | 0 | 2 | |||||||||
| What should the result be? | ||||||||||||||
| Overflow occurs in UB when there is a carry out of the msb. (Value is too large for N bits.) | ||||||||||||||
| What about 2C? | ||||||||||||||
| In our example of 2C addition, there was a carry out of the msb, but the result was correct! | ||||||||||||||
| carry | 1 | 1 | 1 | 1 | ||||||||||
| 1 | 0 | 1 | 1 | -5 | ||||||||||
| 0 | 1 | 1 | 1 | 7 | ||||||||||
| result | 0 | 0 | 1 | 0 | 2 | |||||||||
| In fact, whenever we add a positive and a negative number, overflow won't occur, | ||||||||||||||
| because the result will be less than the magnitude of the larger value. | ||||||||||||||
| When does overflow occur in 2C? | ||||||||||||||