【问题标题】:unsigned short to custom float 16 bit自定义浮点数的无符号短 16 位
【发布时间】:2016-03-09 22:32:26
【问题描述】:

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

所以我对每个 ushort 唯一要做的就是乘以 0.01;

有没有一种方法可以为此创建一个类型,使用 typedef 或 union 或 struct,而不会浪费内存并节省最大 cpu?

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

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

我想要的是某种类型,它的回报已经乘以 0.01 而不是浪费内存

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

有没有更好的办法?

谢谢

【问题讨论】:

  • 什么时候需要转换为浮点数?或者你只需​​要定点数学。如果你只是需要它来存储,你可以使用struct myType{short storage; operator float(){return storage*0.01;}}; 之类的东西(我想你还应该检查类型的对齐方式,以确保你的编译器不会自动将它对齐到 4 个字节)

标签: c++ typedef unions


【解决方案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
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-20
    • 1970-01-01
    • 2011-11-10
    • 2014-07-31
    • 2010-09-24
    相关资源
    最近更新 更多