小编rog*_*erz的帖子

添加签名到无符号时如何判断溢出

我在向无符号位置添加有符号偏移时尝试检测溢出

uint32 position;
int32 offset;  // it could be negative
uint32 position = position+offset;
Run Code Online (Sandbox Code Playgroud)

如何检查结果是溢出还是下溢?

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

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

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

更新:

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

uint32 position;
long offset;  // it could be negative
uint32 position = position+offset;
Run Code Online (Sandbox Code Playgroud)

c unsigned signed overflow underflow

9
推荐指数
1
解决办法
1300
查看次数

标签 统计

c ×1

overflow ×1

signed ×1

underflow ×1

unsigned ×1