Converting floating point to fixed point

后端 未结 6 1862
耶瑟儿~
耶瑟儿~ 2020-12-23 12:13

In C++, what\'s the generic way to convert any floating point value (float) to fixed point (int, 16:16 or 24:8)?

EDIT: For clarification, fixed-poin

6条回答
  •  渐次进展
    2020-12-23 13:12

    There isn't any built in support in C++ for fixed point numbers. Your best bet would be to write a wrapper 'FixedInt' class that takes doubles and converts them.

    As for a generic method to convert... the int part is easy enough, just grab the integer part of the value and store it in the upper bits... decimal part would be something along the lines of:

    for (int i = 1; i <= precision; i++)
    {
       if (decimal_part > 1.f/(float)(i + 1)
       {
          decimal_part -= 1.f/(float)(i + 1);
          fixint_value |= (1 << precision - i);
       }
    }
    

    although this is likely to contain bugs still

提交回复
热议问题