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

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

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

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

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");
``````
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

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

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