c - 在编译时查找任何 float 最接近的 2 次方

标签 c

我需要通过除以 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/

相关文章:

c - "Illegal hardware instruction"来自非常简单的代码

c - 如何在 C 中跳过执行缓冲区溢出的行

c - 应该使用 pthread 通过命令行接受多少线程?

c++ - 计算数字的总和乘以字符串的长度

c - 在 C 中声明字符串/单词变量

c - ARM 程序集 - bl 分支到错误的地址

编译 XFCE4 面板插件

c - 使用分治法的矩阵乘法

java - JNI EXCEPTION_ACCESS_VIOLATION (0xc0000005) msvcr100.dll+0x1ed7 仅适用于 Windows

检查命令行参数中的任何字符是否不是 '1' 或 C 中的 '0'