Undefined when exceeds 64 bit

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

However, in 64-bit systems there is no standard 128-bit integer. Is there an easy way to check for overflow or a way to get 128-bit integers that works on all OS and compilers?

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

Efficiency is not too important, it does not have a processor specificity - ASM.

+1
source share
3 answers

Most of the discussion in this matter applies:

How to detect integer overflow?

Many of the methods used for 32-bit overflows also apply to 64-bit overflows (not all methods discussed use the following larger integer type to handle overflows).

+3
source

this document details interception overflow (c). I don't know if there are better ways to do this in C ++.

+2
source

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

I can’t remember the operatorX syntax from the top of my head (I switched from C ++ to Java long ago), but the sample would be as follows:

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; } 

Similarly for any other arithmetic operation, although it can become very difficult for uncharacteristic functions such as powers, factorials, etc.

However, if you build those of the basic arithmetic building blocks, they will work.

+1
source

Source: https://habr.com/ru/post/901073/


All Articles