gre*_*det 7 c embedded overflow
我在16位字段上有一个计数器,它由硬件外设随时间递增/递减.
我定期对其值进行采样,将差值加到32位字段中.
我的问题是在计算差异时检测16位字段的上溢/下溢.
让我们举一个例子:
在样本n-1,计数器值Vn-1是65530.
作为样本n,计数器值Vn是4.
计数器增加10.但是差值(Vn-Vn-1),将是像65529(不确定的确切值).
我发现检测此溢出的唯一方法是将差值与大于最大增量的固定值进行比较(我选择10000).
您是否知道在不与此主观价值进行比较的情况下管理此溢出的解决方案?
这是一个代码示例:
static sint32 overallCount = 0;
sint32 diff;
static sint16 previousValue = 0;
sint16 currentValue;
currentValue = sampleValue();
diff = ((sint32) currentValue) - previousValue;
if(diff > 10000) {
diff -= 65536;
} else if ((-diff) > 10000) {
diff += 65536;
}
overallCount += diff;
Run Code Online (Sandbox Code Playgroud)
我之前的回答有一些错误,所以我重写了它,但想法是一样的,正确使用无符号类型.
使currentValue和previousValue都是所选大小的无符号整数(例如uint16_t).然后只是减去它们.由于差异将被隐式提升为intif int比较大的类型uint16_t,因此您需要将结果转换或隐式转换回uint16_t.所以:
static uint16_t previousValue;
uint16_t currentValue = sampleValue();
uint16_t diff = currentValue - previousValue;
Run Code Online (Sandbox Code Playgroud)
这会在赋值中使用隐式转换,但如果您愿意,可以进行转换.
| 归档时间: |
|
| 查看次数: |
3869 次 |
| 最近记录: |