Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting "carry" in x + y [duplicate]

Tags:

c++

c

math

Possible Duplicate:
Best way to detect integer overflow in C/C++

If I have an expression x + y (in C or C++) where x and y are both of type uint64_t which causes an integer overflow, how do I detect how much it overflowed by (the carry), place than in another variable, then compute the remainder?

like image 348
Clark Gaebel Avatar asked May 23 '11 01:05

Clark Gaebel


1 Answers

The remainder will already be stored in the sum of x + y, assuming you are using unsigned integers. Unsigned integer overflow causes a wrap around ( signed integer overflow is undefined ). See standards reference from Pascal in the comments.

The overflow can only be 1 bit. If you add 2 64 bit numbers, there cannot be more than 1 carry bit, so you just have to detect the overflow condition.

For how to detect overflow, there was a previous question on that topic: best way to detect integer overflow.

like image 64
Himadri Choudhury Avatar answered Oct 14 '22 20:10

Himadri Choudhury