将溢出转换为负数

标签 c overflow

是否有一种简单的方法可以用负值替换倒计时的溢出?

例如 32 位变量。可能的值为 0x00000000 - 0xFFFFFFFF。当我从最低可能值 (0x00000000 - 1) 中减去 1 时,结果是 0xFFFFFFFF。如何更改运算以给出 -1 的结果?

最佳答案

Is there an easy way to replace an overflow at counting down with a negative value?

使用更广​​泛的数学是一种直接的方法。

“示例 32 位变量。可能的值为 0x00000000 - 0xFFFFFFFF”意味着该变量是某种无符号类型,例如 uint32_t

<小时/>

根据OP报告,从(uint32_t)0中减去1是(uint32_t)0xFFFFFFFF。因此,请使用更广泛的有符号数学,例如long long(至少是64位)或int64_t

// Insure subtraction is done using `long long` math with 1LL
long long result = var_uint32_bit - 1LL;
<小时/>

或者,代码可以坚持使用相应的相同宽度的有符号类型。

// Only non-implementation defined for values 0...0x7FFFFFFF
int32_t result = (int32_t)var_uint32_bit - 1;

(int32_t)var_uint32_bit 在将无符号类型转换为有符号整数类型方面存在限制。

Otherwise, the new type is signed and the value cannot be represented in it; either the result is implementation-defined or an implementation-defined signal is raised. C11dr §6.3.1.3 3

关于将溢出转换为负数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42957736/

相关文章:

html - 溢出滚动在类(class) child 中不起作用

javascript - 调整溢出元素的大小 :auto taking scrollbars into account

html - 溢出, float ,高度困惑

asp.net - IE7 不自动显示滚动条?

javascript - 将 td 内容溢出到下一个 td 元素,而不在 HTML 表格中进行替换

字符指针溢出

c# - 在基于 Map Object 2.4 的应用程序中读取 .dgn v8 文件

c - 使用 Cygwin、cmd 和 Sublime Text 2 编译简单 C 程序时出错

c - 为什么我的程序结合了两个 printf 命令?

c - 用 LD_PRELOAD 覆盖 execve() 有时只有效