c中的按位溢出检查

Gek*_*tek 4 c operations bit-manipulation overflow

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

也没有强制转换,整数总是 32 位

小智 5

/* 
 * 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));
}
Run Code Online (Sandbox Code Playgroud)

  • `sizeof(int)*8-1` 对我来说看起来比 `31` 干净。 (2认同)