我在向无符号位置添加有符号偏移时尝试检测溢出
uint32 position;
int32 offset; // it could be negative
uint32 position = position+offset;
Run Code Online (Sandbox Code Playgroud)
如何检查结果是溢出还是下溢?
我想到了一个丑陋的方式,但不确定它的正确性.
offset < 0 && position + offset >= positionoffset > 0 && position + offset <= position而且我也想知道是否有一种更优雅的方式来做到这一点.
更新:
如果偏移很长,最好的解决方案是什么?
uint32 position;
long offset; // it could be negative
uint32 position = position+offset;
Run Code Online (Sandbox Code Playgroud)