c - 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
}
解决方案
推荐阅读
- r - 删除R中数据框中的数字和数字后面的句点?
- javascript - Vuejs:数据属性更改时组件不会重新渲染
- flutter - 计数器不改变其状态
- dataframe - 读取Parquet文件时spark如何决定列顺序
- javascript - 粘性导航栏,滚动到第一个元素不精确
- javascript - 在 webpack 中,CompatibilityPlugin 做了什么?
- c# - 调整网格内的图像大小以始终适合可用空间
- python - Scrapy errback 无法捕获所有错误
- .net - Visual Studio 未加载模块(因此没有要命中的断点)
- php - 按条款显示自定义帖子