是否有一种简单的方法可以用负值替换倒计时的溢出?
例如 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/