Jul 01, 2006 18:37
I just created a super-fast method to detect signed overflow in C++.
int r = a + b;
bool Overflow = ((~(a ^ b)) & (b ^ r)) >> 0x1f;
And one for subtraction:
int r = a - b;
bool Overflow = ((~(b ^ r)) & (a ^ b)) >> 0x1f;
It relies on 2's compliment, though, so it wouldn't work on 1's compliment machines... not that it really matters on modern CPUs. :)