1

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.

Ivan
  • 347
  • 2
  • 4
  • 16
Chris Jefferson
  • 7,225
  • 11
  • 43
  • 66

3 Answers3

3

Much of the discussion in this question applies:

How to detect integer overflow?

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).

Community
  • 1
  • 1
Michael Burr
  • 333,147
  • 50
  • 533
  • 760
2

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

Community
  • 1
  • 1
Draemon
  • 33,955
  • 16
  • 77
  • 104
  • In C++ I would use templates instead of the macros in that document. Eliminate the need for typeof(). – Justsalt Oct 15 '08 at 15:38
1

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
  • 854,327
  • 234
  • 1,573
  • 1,953