Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading