gpt4 book ai didi

c - 在嵌入式上下文中缩放值的高效程序

转载 作者:行者123 更新时间:2023-12-04 08:42:28 26 4
gpt4 key购买 nike

我想在 0 和 32767 之间缩放我的输入值。对于上下文,这个程序在 ARM M0 上运行,我想避免任何浮点操作。我的输入类型是 u32,输出类型是 u16。到目前为止,我有这个,在进行大型乘法时我明确检查溢出。如果没有,我只是继续乘以数字。这种检查溢出的方法是实现所需缩放的有效方法吗?

uint16_t scaling(uint32_t in, uint32_t base)
{
uint32_t new_base = INT16_MAX; // 32767

if (in >= base) {
return (uint16_t)new_base;
}

if (in != ((in * new_base) / new_base) ) {
// overflow, increase bit width!
uint64_t tmp = in * (uint64_t)new_base;
tmp /= base;
return (uint16_t)(tmp);
}

// simply multiply
uint32_t tmp = (in * new_base) / base;

if (tmp > new_base) {
tmp = new_base; // clamp
}

return (uint16_t)tmp;
}
例如,对于 (in=200000, base=860000) 的样本“大”输入,预期输出为 7620(该程序确实会回馈)

最佳答案

OP 代码的以下变体预先计算了阈值,其中 in * new_base溢出到64位,保存最后检查if (tmp > new_base)这是多余的一次 in < base .

uint16_t scaling(uint32_t in, uint32_t base)
{
static const uint32_t new_base = INT16_MAX; // 2^15 - 1 = 32767
static const uint32_t in32 = (uint32_t)(((uint64_t)UINT32_MAX + 1) / INT16_MAX); // 2^32 / (2^15 - 1) = 131076

if (in >= base) {
return (uint16_t)new_base;
}

if(in < in32) {
return (uint16_t)((in * new_base) / base);
}

return (uint16_t)(((uint64_t)in * new_base) / base);
}
作为旁注,至少 one compiler (使用默认优化运行)将替换乘法 in * new_base用更便宜的 (in << 15) - innew_base = INT16_MAX已声明 const uint32_t但不是当声明为只是 uint32_t .

关于c - 在嵌入式上下文中缩放值的高效程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64489980/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com