unsigned short to custom float 16 bit

时间:2016-03-09 14:27:35

标签: c++ typedef unions

我有一些大浮点数组,但我不需要所有的32位精度,需要保存ram,所以我使用无符号短类型,因为我只需要2位小数,最大值不要超过654。

因此,我唯一需要做的就是用0.01;

有没有办法可以使用typedef或union或struct为此创建一个类型,而不会浪费ram并保存最大的cpu?

我现在拥有的是这个,而不是cpu友好的我猜

vector<unsigned short> vect(bigvalue);
for(int i=0;i<bigvalue;i++)(vect[i]*0.01)*some expression...

我想要的是某种类型,返回已经乘以0.01而不是浪费ram

vector<float16bit> vect(bigvalue);
for(int i=0;i<bigvalue;i++)(vect[i])*some expression...

有更好的方法吗?

由于

1 个答案:

答案 0 :(得分:-1)

您可以使用重载算术运算符(+ - * /等)创建类(存储无符号短号)。这些操作员在完成工作时应考虑因数为100。

class FastFloat
{
    unsigned short n;

    ...

    FastFloat(const unsigned short n): n(n){}

    FastFloat operator+(const FastFloat &ff)
    {
        return FastFloat(this->n + ff.n);
    }

    // same for other operators
};