我正在尝试在 C++ 中创建一个基于模板的任意精度浮点库,它支持可以指定为模板参数的变量指数和变量尾数。我已经开发了一个基于模板的定点库。我想要的实现类型是:
template<int EXPONENT_BITS, int MANTISSA_BITS>
struct fp_float
{
<some_data_type_to_store_exponent_and_mantissa_values>;
};
我无法找到合适的数据类型来存储指数,因此我不会使用比代码所需更多的位。我想到了使用 intn_t
其中 n = {8, 16, 32, 64}
但是如果我声明 fp_float<3,11>
它将使用 8
EXPONENT
的位和 16
MANTISSA
的位.
因此,它使整个库变得无用,因为它使用了比指定精度应该使用的更多的资源。
我想知道是否有任何其他任意精度数据类型可以满足我的目的。
我确实遇到了一些任意精度的库,但这些库有一些代码结构,无法使用高级综合将其合成到硬件描述中(这就是我制作这个库的原因)。
最佳答案
这对您来说是有效的解决方案吗? base_int_t 是一种特征类型,它为您提供要在后续位域定义中使用的基本类型。下面的代码缺少 N > 2
的特化// gives an integer type fitting in N bytes
template <int N>
struct base_int_t
{
typedef int type;
};
// specializations
template <>
struct base_int_t<1>
{
typedef unsigned char type;
};
template <>
struct base_int_t<2>
{
typedef unsigned short type;
};
// add suitable definitions for N = 3,4...8. For N = 3 and 4 type is unsigned int
template <int EXP_BITS, int MANTISSA_BITS>
struct fp_float
{
// template argument is the number of bytes required
typedef typename base_int_t<(EXP_BITS + MANTISSA_BITS + 7) / 8>::type type;
type mantissa : MANTISSA_BITS;
type exponent : EXP_BITS;
};
typedef fp_float<3, 11> fp_3_11_t;
fp_3_11_t fp;
关于c++ - 用于高级综合的任意精度浮点库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31400946/