c - 有符号加无符号时如何判断溢出

标签 c overflow unsigned signed underflow

我试图在将有符号偏移量添加到无符号位置时检测溢出

uint32 position;
int32 offset;  // it could be negative
uint32 position = position+offset;

如何判断结果是上溢还是下溢?

我想到了一个丑陋的方法,但不确定它的正确性。

  • 下溢:offset < 0 && position + offset >= position
  • 溢出:offset > 0 && position + offset <= position

而且我也想知道是否有更优雅的方式来做到这一点。

更新:

如果偏移量很长,最好的解决方案是什么?

uint32 position;
long offset;  // it could be negative
uint32 position = position+offset;

最佳答案

您的测试是正确的。我现在没有看到更优雅的方式,也许没有。

为什么条件是正确的:uint32_t 上的算术运算是算术模 2^32。从 int32_t 转换而来至 uint32_t通常是对位模式的重新解释(无论如何,正如@caf 指出的那样,它在这里以 2^32 为模进行缩减,因此绝对有效)。关注positionoffset作为任意精度整数。溢出发生当且仅当
position + offset >= 2^32 .但是offset < 2^31 , 所以 position + offset < position + 2^31 ,小于 position + 2^32 ,下一个减少到 position 的值模 2^32,所以 uint32_t , 然后 position + offset < position .另一方面,如果 offset > 0position + offset < position ,显然发生了溢出。当且仅当 position + offset < 0 时才会发生下溢作为数学整数。自 offset >= -2^31 , 类似的推理表明当且仅当 offset < 0 && position + offset > position 发生下溢.

关于c - 有符号加无符号时如何判断溢出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7992490/

相关文章:

c++ - 从轮廓 OpenCV 中提取矩形

c - C中的数组索引限制

c - select() 在 SIGALRM 时返回套接字准备就绪

c - 如何评估开关盒?

javascript - 溢出-x : visible; doesn't work with overflow-y: auto; any workaround?

c++ - 使用 SSE 计算无符号整数之间的绝对差

c - itoa() c 实现 int min 下溢

html - 允许 Fixed div 随内容扩展高度

c - C 中无符号变量的算术运算

java - 如何在java中生成0到2^32-1之间的随机数