   # What is the simples way to check if the sum of two unsigned integers has resulted in an overflow.

+6 votes
353 views

What is the simples way to check if the sum of two unsigned integers has resulted in an overflow. posted Oct 29, 2013
Share this question
1. If highest bit of both the integers is 1 then definite overflow.
2. If highest bit of both the integers is 0 then definite no overflow.
3. If highest bit of only one then is 1 then may or may not be overflow.
Extending Salil's Comment

1. If highest bit of both the integers is 1 then definite overflow.
2. If highest bit of both the integers is 0 then definite no overflow.
3. If highest bit of only one then
Assume N1 has most significant bit as 1 and N2 has most significant bit is zero
P1 = first occurrence of 0 in N1 (most significant to least significant)
P2 = first occurrence of 1 in N2

P1 < P2  => will not overflow
P1 > P2 => Will overflow
P1 == P2 => left shift numbers by P1 and repeat from step 1

## 2 Answers

0 votes

Try this

``````int uadd32(uint32 a,uint32 b) {
unsigned long long x=(unsigned long long) a+b;
if (x>0xffffffff) return 0; // 0 means overflow
return 1; // 1 means no overflow
}
`````` answer Oct 30, 2013
–2 votes

May not be fastest solution -
a = b+c
if a is truncated because of overflow the c != a-b

Code

``````a = b + c;
if (c == (a-b))
printf("No Overflow");
else
printf("Overflow");
`````` answer Oct 30, 2013
Consider this example for 8 bit unsigned integer

a = 255, b = 254
c = a + b = 253
c - a = 254
c - b = 255
Sorry, I should have tested...(it was a mathematical solution need to code it)
Similar Questions
+6 votes

Write a program to reverse the bits of an unsigned integer ??

+8 votes

Divide the array in two subarrays of n/2 sizes each such that the difference of the sum of two subsets is as minimum as possible. If n is even, then sizes of two subarray must be n/2 and if n is odd, then size of one subarray must be (n-1)/2 and size of other subset must be (n+1)/2.

+1 vote

Say you are given

``````int a[ ] = {1,2,3,4};
int b[ ] = {4,3,2,1};
int S = 5;
``````

Now the task is to find all pairs of two number which adds up to S (One number from a and other number from b).