我需要通过除以 2 的最接近的较高幂来将所有 float 缩放到 [-1,1]
范围。代码需要固定为 Q0.31 -点,所以没有 float 。
例如,10.75 除以 16、20.91 除以 32、1000.17 除以 1024 等等,一直到 2^31。
我需要在编译时完成缩放。
例如:
#define PARAMETER1 10.0f // this could be changed in various builds
#define PARAMETER1_SCALE ( CALC_SCALE(PARAMETER1) )
#define float_to_fixed(x) ( (int)( (float)(x)*(float)0x80000000 ) )
int main()
{
int par1 = float_to_fixed( PARAMETER1/PARAMETER1_SCALE );
// use par1 here
// ...
// then descale using PARAMETER1_SCALE again
}
是否有 C 宏 CALC_SCALE
可以计算此值?
最佳答案
这个怎么样:
#include <math.h>
#define collapse(value) (value < 0 ? value / pow(2, ceil(log2(value * -1))) : value / pow(2, ceil(log2(value))))
int main() {
cout << collapse(10.75) << endl;
cout << collapse(20.91) << endl;
cout << collapse(-1) << endl;
cout << collapse(-2.5) << endl;
cout << collapse(5.7) << endl;
}
输出是:
0.671875
0.653438
-1
-0.625
0.7125
关于c - 在编译时查找任何 float 最接近的 2 次方,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41720702/