本文介绍了创建方法,使用按位运算检查x + y是否溢出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在C中使用按位运算创建一个方法,该方法检查x + y是否溢出.我最多只能使用以下20种操作; ! 〜& ^ | +<< >>请记住,我必须同时测试负数和正数.

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.

我已经尝试过几次以使其正常运行.我的逻辑声音吗?我要经过:如果(x + y)小于x,则表明它已溢出.根据这种逻辑,我写了这个;

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

谢谢!

推荐答案

这应该有效,但它不仅使用按位运算符,而且还适用于带符号运算符:

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

这篇关于创建方法,使用按位运算检查x + y是否溢出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-26 11:55