what's the simplest way to detect overflow for adding two integers?
Sunday, June 06, 2004
a + b = c
Couple of thoughts:
1. many processors do have this info available after the operation in some sort of a FLAG/condition register - platform dependent code.
2.1 for unsigned ints, if result is numerically lower then any of a or b => overflow
2.2 for signed ints, if sings of a & b are not equal, there is no way an overflow can happen. For equal signs, if the sign of result is different then those of a & b => overflow
(This rule seems to be complicated to code, but think XOR)
3. do the operation also on wider type then int (maybe long long) and compare results, if unequal =>overflow.
Thursday, June 10, 2004
Fog Creek Home