Create method which checks if x + y will overflow using bitwise operations

巧了我就是萌 提交于 2019-12-04 17:12:21

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;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!