浮动到固定转换

Float to fixed conversion

这是一个基本问题,但我很困惑。

我有一个格式为 1.4.12 的寄存器。这意味着它需要一个浮点数并取范围 -15.9999 - 15.9999,这是正确的,还是有多少个 9?我对范围感到困惑。

我需要将 C++ 浮点数转换为定点数并将其放入寄存器中吗?是否有任何 std:: 库可以在 C 中执行此操作?如果没有,是否有人可以指出任何标准代码?

还有,请问如何将fixed转float比较好?

自己做这个很简单:

typedef int32_t fixed;

fixed float_to_fixed(float x)
{
    return (fixed)(x * 65536.0f / 16.0f);
}

请注意,这没有范围检查,因此如果 x 可能超出您的定点类型的有效范围,那么您可能需要添加一些检查并根据需要饱和或抛出错误。

另一个方向的转换同样如此:

float fixed_to_float(fixed x)
{
    return (float)x * 16.0f / 65536.0f;
}

(这个当然不需要任何范围检查。)

如果你需要使用定点,那么你必须实现加法和乘法运算。在那种情况下,您需要担心为小数部分分配了多少位以及为整数部分分配了多少位。然后你可以根据自己的喜好进行“移位”操作。

在下面的代码片段中,我通过为小数部分分配 22 位和为整数部分分配 9 位来实现定点。 (附加位将用于符号)

在乘法中,我首先扩展了每个值的位长以避免溢出。乘法后左移恰好保留相同的小数部分作为乘法的输出

此外,我为输出添加了饱和度,以避免任何溢出(如果发生溢出,则输出将保持它可以保持的最大绝对值,而不管符号如何)

#include <stdio.h>
#include <math.h>
#include <stdint.h>

#define fractional_bits 22
#define fixed_type_bits 32

typedef int32_t fixed_type;
typedef int64_t expand_type;

fixed_type float_to_fixed(float inp)
{
    return (fixed_type)(inp * (1 << fractional_bits));
}

float fixed_to_float(fixed_type inp)
{
    return ((float)inp) / (1 << fractional_bits);
}

fixed_type fixed_mult(fixed_type inp_1, fixed_type inp_2)
{
    return (fixed_type)(((expand_type)inp_1 * (expand_type)inp_2) >> fractional_bits);
}

fixed_type fixed_add(fixed_type inp_1, fixed_type inp_2)
{
    fixed_type inp_1_sign = inp_1 >> (fixed_type_bits - 1);
    fixed_type inp_2_sign = inp_2 >> (fixed_type_bits - 1);
    fixed_type add = inp_1 + inp_2;
    fixed_type add_sign = add >> (fixed_type_bits - 1);

    if (inp_1_sign != inp_2_sign)
    {
        return add;
    }
    else if (add_sign == inp_1_sign)
    {
        return add;
    }
    else if (add_sign == -1)
    {
        return ((1 << (fixed_type_bits - 2)) - 1 + (1 << (fixed_type_bits - 2)));
    }
    else if (add_sign == 1)
    {
        return (1 << (fixed_type_bits - 1));
    }
}