Carry over with integer operations

Hi all,

I want to know how can I figure, when I am multiplying or adding two integers, whether there has been an automatic carry over due to the integers being too large.

I am doing rather heavy mathematical computations with rational numbers, and I have no control on how large the numerators/denominators of my fractions can get. (in fact, the number of rational numbers I need to compute is one of the unknowns I am trying to find with my program).

At the moment I made my program alert me when the numerators/denominators of my fractions exceed 2^20, which, unfortunately, happens quite quickly.

Is there a register / flag / anything that one can check for carry over?
There are processor flags (at least on Intel) that mark carries and overflows, but I don't know if you can use them if you let the compiler generate the instructions to perform the arithmetic.

Check the result against the input.

For example:
1
2
3
c = a + b;
if (c <= max( a, b ))
  overflow();


If you know that your code will be used on only one type of hardware (such as the already-mentioned Intel x86 series), then use some inline assembly to do it and check the x86 carry flag and/or overflow flag flag. (There are conditional jump opcodes to do that: google "jcc opcode".)

Other hardware, such as MIPS, doesn't track such things --at least not easily.

Good luck!

[edit] BTW, you might want to check out the GNU MP Bignum Library http://gmplib.org/
Last edited on
thanks for the advice. Also looked at the library in question: it looks quite good, but I doubt I will use it (I am one of those weird people who like to write all the important code themselves :)
Ah ha. NIH syndrome.

In that case you have to be careful with a lot of edge cases.

For example, the above code works only if a and b are both non-negative.
Yoinks! Sorry about that.
1
2
3
c = a + b;
if ((unsigned)c <= max( (unsigned)a, (unsigned)b ))
  overflow();

Topic archived. No new replies allowed.