浮动到固定的转换

Float to fixed conversion

本文关键字:转换      更新时间:2023-10-16

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

我有一个格式为1.4.12的寄存器。这意味着它需要一个浮动,取值范围为-15.9999-15.9999,是正确的吗,还是多少个9?我被范围弄糊涂了。

我需要将c++浮点转换为定点并将其放入寄存器中?在C中有没有std::库可以做到这一点?如果没有,有没有任何标准代码可以让我参考?

此外,如何将固定转换为浮动会很好?

自己做这件事很简单:

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));
    }
}