问题
I need to create a method in C using bitwise operations which checks if x + y will overflow or not. I can only use a maximum of 20 of the following operations; ! ~ & ^ | + << >> Keep in mind I have to test for both negative and positive numbers.
I've tried several times to make it work. Is my logic sound? I'm going by: if (x + y) is less than x, then it has overflowed. Based on that logic, I wrote this;
int addOK(int x, int y)
{
int sum = x + y;
int nx = ((~x) + 1);
int check = (sum + nx)>>31;
return !check;
}
Thank you!
回答1:
This should work, but it doesn't use only bitwise operator, but it work for signed :
int addOK(int x, int y)
{
int check;
if (greaterThan(0, x^y))
check = 0;
else if (greaterThan(x, 0))
check = greaterThan(y, INT_MAX -x);
else
check = greaterThan(INT_MIN -x, y);
return check;
}
int greaterThan(int first, int second) {
/* first > second means second - first is less than 0
shift the sign bit and then compare it to 1 */
return (second + (~first +1)) >> ((sizeof(int) * 8) -1) & 1;
}
If the two numbers are both positive should be enough :
int addOK(int x, int y) {
if(x^y < 0)
return 0;
return 1;
}
来源:https://stackoverflow.com/questions/10154975/create-method-which-checks-if-x-y-will-overflow-using-bitwise-operations