【发布时间】:2013-02-06 22:42:05
【问题描述】:
谁能帮我解释一下这个功能,谢谢!
int overflow(int x, int y)
{
int result, non_overflow, overflow, result_sign, mask;
result = x + y;
result_sign = result >> 31; //Need help starting from here... I know
//it is shifting 31 bits... but why??
non_overflow = ((x ^ y) | ~(y ^ result)) >> 31;
overflow = ~non_overflow;
mask = overflow << 31;
return (non_overflow & result) | (overflow & (result_sign ^ mask));
}
【问题讨论】:
-
您是否采用了两对数字(一对在 add 时溢出,一对没有)并手动或在调试器中遍历算法以查看会发生什么在每个操作中?
-
没想到。谢谢。顺便说一句..你怎么让它溢出?
-
最简单的方法?
overflow(MAX_INT,MAX_INT)应该这样做。但这一切都需要在 32bit-int平台上运行,否则无论如何这都行不通。不过,看起来您已经从标签中知道了这一点。
标签: c 32-bit integer-overflow integer-arithmetic