c中的按位溢出检查

时间:2012-04-09 19:41:07

标签: c overflow bit-manipulation operations

我正在尝试编写两个函数来检查/防止c中的溢出(仅使用!〜|& ^ +)但是无法得到它。第一个是某个二进制补码/ signed int将适合一个certatin的位数:fitsB(int x,int n)其中是int,n是要使用的位的大小。还有一个函数,它将检查两个整数在加在一起时是否不会溢出:overflowInt(int x,int y)。如果他们是无符号的整数,我可以得到它,但负面的东西只会让我更难。谁知道怎么样?

也没有强制转换,而且总是32位

3 个答案:

答案 0 :(得分:3)

/* 
 * addOK - Determine if can compute x+y without overflow
 *   Example: addOK(0x80000000,0x80000000) = 0,
 *            addOK(0x80000000,0x70000000) = 1, 
 *   Legal ops: ! ~ & ^ | + << >>
 *   Max ops: 20
 *   Rating: 3
 */
 int addOK(int x, int y) {
  // Find the sign bit in each word
  //if a and b have different signs, you cannot get overflow.
  //if they are the same, check that a is different from c and b is different from c, 
  // if they are the same, then there was no overflow.
  int z=x+y;
  int a=x>>31;
  int b=y>>31;
  int c=z>>31;
  return !!(a^b)|(!(a^c)&!(b^c));
}

答案 1 :(得分:0)

如果x

溢出问题需要更多信息。如果将它们分配给长(或双),则两个整数不会溢出。

答案 2 :(得分:0)

使用上面的例子(Adam Shiemke),你可以找到最大(正)值和最小值(负)来得到n个比特的范围。 2 ^(n-1)(来自Adam的例子)和减1表示可以用n位表示的最大值/正数。对于最小值,否定2 ^(n-1)以获得最小值x =&gt; - (2 ^(N-1)); (注意&gt; = not&gt;表示最小范围)。例如,对于n = 4比特,2 ^(4-1)-1 = 2 ^ 3 -1 = 7,因此x <= 7且x> = -8 =( - (2 ^(4-1)) )。

这假设初始输入不会溢出32位量(希望在该条件下发生错误)并且您使用的位数小于32(因为您为负范围添加1并且如果您有32位,它会溢出,见下面的解释)。

要确定添加是否会溢出,如果您有最大值,则x + y <=最大值。通过使用代数,我们可以得到y <=最大值 - x。然后,您可以比较y的传入值,如果不符合条件,则添加将溢出。例如,如果x是最大值,则y <= 0,因此y必须小于或等于零,否则加法将溢出。