首页 > 解决方案 > C在减法期间检查溢出

问题描述

我一直在尝试确定减去两个 32 位数字时是否存在溢出。我得到的规则是:

Can only use: ! ~ & ^ | + << >>
 *   Max uses: 20
Example: subCheck(0x80000000,0x80000000) = 1,
 *       subCheck(0x80000000,0x70000000) = 0
No conditionals, loops, additional functions, or casting

到目前为止我有

int dif = x - y; // dif is x - y
int sX = x >> 31; // get the sign of x
int sY = y >> 31; // get the sign of y
int sDif = dif >> 31; // get the sign of the difference
return (((!!sX) & (!!sY)) | (!sY)); // if the sign of x and the sign of y 
                                    // are the same, no overflow. If y is 
                                    // 0, no overflow.

我现在意识到我不能在实际函数中使用减法(-),所以我的整个函数无论如何都没用。如何使用与减法不同的方法并仅使用按位运算确定是否存在溢出?

标签: cbitwise-operatorsinteger-overflow

解决方案


谢谢大家的帮助!这是我想出解决我的问题:

int ny = 1 + ~y; // -y
int dif = x + ny; // dif is x - y
int sX = x >> 31; // get the sign of x
int sY = y >> 31; // get the sign of -y
int sDif = dif >> 31; // get the sign of the difference
return (!(sX ^ sY) | !(sDif ^ sX));

我尝试过的每个案例都有效。我改变了@HackerBoss 的建议,通过获取 y 而不是 ny 的符号,然后在 return 语句中反转这两个检查。这样,如果符号相同,或者结果的符号和 x 的符号相同,则返回 true。


推荐阅读