When adding 8 bit unsigned integers (type unsigned char), overflow occurs if there is a carry out of bit position 7. But the carry is simply discarded.
What is the value of the carry into the 8th position? Answer: 28 = 256.
For mathematical binary addition, overflow doesn't occur. Mathematically, there is no largest integer.
If overflow occurs addition using 8 bit unsigned integers, discarding the carry is the same as subtracting 256 from the mathematical addition result.
Examples
unsigned char x | unsigned char y | unsigned char z = x + y (mathematically) |
(z <= 255)? z : z - 256 |
---|---|---|---|
254 | 1 | 255 | 255 |
254 | 2 | 256 | 0 (= 256 - 256) |
254 | 3 | 257 | 1 (= 257 - 256) |