c++ - 将 float 转换为定点数

标签 c++ fixed-point

在 C++ 中,将任何浮点值 (float) 转换为 fixed point 的通用方法是什么? (int, 16:16 或 24:8)?

编辑:为了澄清,定点值有两个部分:整数部分和小数部分。整数部分可以用有符号或无符号整数数据类型表示。小数部分由无符号数据整数数据类型表示。

为了清楚起见,让我们用金钱做一个类比。小数部分可能代表美分——一美元的小数部分。 'cents' 数据类型的范围是 0 到 99。如果将 8 位无符号整数用于定点数学,那么小数部分将被分成 256 个可整除的部分。

我希望这能解决问题。

最佳答案

给你:

// A signed fixed-point 16:16 class
class FixedPoint_16_16
{
    short          intPart;
    unsigned short fracPart;

public:
    FixedPoint_16_16(double d)
    {
        *this = d; // calls operator=
    }

    FixedPoint_16_16& operator=(double d)
    {
        intPart = static_cast<short>(d);
        fracPart = static_cast<unsigned short>
                    (numeric_limits<unsigned short> + 1.0)*d);
        return *this;
    }

    // Other operators can be defined here
};

编辑:这是一个更通用的类,它基于另一种处理定点数的常用方法(KPexEA 指出了这一点):

template <class BaseType, size_t FracDigits>
class fixed_point
{
    const static BaseType factor = 1 << FracDigits;

    BaseType data;

public:
    fixed_point(double d)
    {
        *this = d; // calls operator=
    }

    fixed_point& operator=(double d)
    {
        data = static_cast<BaseType>(d*factor);
        return *this;
    }

    BaseType raw_data() const
    {
        return data;
    }

    // Other operators can be defined here
};


fixed_point<int, 8> fp1;           // Will be signed 24:8 (if int is 32-bits)
fixed_point<unsigned int, 16> fp1; // Will be unsigned 16:16 (if int is 32-bits)

关于c++ - 将 float 转换为定点数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/187713/

相关文章:

c++ - 初始化时无法将 ‘<brace-enclosed initializer list>’ 转换为 ‘int*’

c++ - 什么文件格式适合记录/配置文件?

c++ - 错误 : no type named 'vector' in namespace 'std'

opencv - 定点整数的哈里斯角响应?

c++ - 关于如何使用此代码段实现 SFINAE 的问题

c++ - 类内部类链接问题的静态constexpr

vhdl - 二进制定点乘法

c - libfixmath 未定义引用

c - 定点码分理解

c# - 不安全的指针操作