tags:

views:

662

answers:

3

In my current 32-bit application, I check (very occasionally) for overflow by doing operations on 64-bit integers.

However, on 64-bit systems there does not seem to be a standard 128-bit integer. Is there a simple way of checking for overflow, or a way of getting 128-bit integers, which works on all OSes and compilers?

I tried using GMP as a more generic solution, but it is a little heavyweight for my requirements.

Efficiency is not too important, no processor specific-ASM is.

+2  A: 

this document talks about catching overflows (in c) in detail. I don't know if there are better ways of doing this in C++.

Draemon
In C++ I would use templates instead of the macros in that document. Eliminate the need for typeof().
Justsalt
+3  A: 

Much of the discussion in this question applies:

http://stackoverflow.com/questions/199333/best-way-to-detect-integer-overflow-in-cc

Many of the techniques used for 32-bit overflow chacking apply to 64-bits as well (not all of the techniques discussed use the next larger integer type to handle the overflow).

Michael Burr
+1  A: 

One solution would be to create a class around the 64-bit int which overrode the arithmetic operators to check before performing the operation.

I can't remember the operatorX syntax off the top of my head (I switched from C++ to Java a long time ago) but a sample would be:

int64 myint64::add (int64 a, int64 b) {
    if (MAX_INT64 - a > b) {
        // error condition here.
    }
    return a + b;
}
int64 myint64::mul (int64 a, int64 b) {
    if (MAX_INT64 / a > b) {
        // error condition here.
    }
    return a * b;
}

Similar for any other arithmetic operation, although this could get very complicated for non-basic functions such as powers, factorials and such.

However, if you build those from the basic arithmetic building blocks, they'll work.

paxdiablo