首页 > 解决方案 > C中的按位加法溢出检查

问题描述

我正在尝试编写一个函数,如果发生溢出则返回 0,否则返回 1。我仅限于按位函数,没有强制转换,整数总是 32 位。

我似乎遇到了 addOK(0x80000000,0x80000001) 返回 1 而不是 0 的问题,我认为这是因为 notsum = !(x + y) 不等于 0。我不知道如何解决这个问题。有任何想法吗?

/* 
 * addOK - Determine if can compute x+y without overflow
 *   Example: addOK(0x80000000,0x80000000) = 0,
 *            addOK(0x80000000,0x70000000) = 1, 
 *            addOK(0x80000000,0x80000001) = 0,
 *   Legal ops: ! ~ & ^ | + << >>
 *   Max ops: 20
 *   Rating: 3
 */
int addOK(int x, int y) {
  int notsum = !(x + y); // 0 if true, 1 if false 
  int mask = notsum + ~0; // ~0 is all 1s! overflow to 0s if notx is false
  return (1 & mask) | (0 & ~mask); // mask is 1s if x is true
}

标签: cbit-manipulationcomputer-sciencebitwise-operators

解决方案


推荐阅读