Search code examples
cgccclang

Arithmetic which gives the lowest 64 bits on overflow


In C unsigned integer arithmetic wraps around on overflow and signed arithmetic is undefined on overflow. I would like to have 64 bit integer arithmetic (+,-,*) so that on overflow the result is the lowest 64 bits. Is this possible?

I don’t want a wrapped around result. What I am looking is equivalent to casting the integers to 128 bit types, performing the operation, taking the lowest 64 bits and casting back to the 64 bit type.


Solution

  • Cast the operands to the unsigned type (of the same size) first, perform the operation, then cast back to the signed type.

    It's easy to prove for + and -. Wasn't certain about *, but it also seems to give the correct result.


    GCC and Clang also have __builtin_{add,sub,mul}_overflow, which always wrap around, and also report whether or not an overflow occured. They work with any integer type.

    int a = 10, b = 20, result;
    bool overflowed = __builtin_add_overflow(a, b, &result);