Converting floating point to fixed point

后端 未结 6 1861
耶瑟儿~
耶瑟儿~ 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 12:55

    **** Edit** : My first comment applies to before Kevin's edit,but I'll leave it here for posterity. Answers change so quickly here sometimes!

    The problem with Kevin's approach is that with Fixed Point you are normally packing into a guaranteed word size (typically 32bits). Declaring the two parts separately leaves you to the whim of your compiler's structure packing. Yes you could force it, but it does not work for anything other than 16:16 representation.

    KPexEA is closer to the mark by packing everything into int - although I would use "signed long" to try and be explicit on 32bits. Then you can use his approach for generating the fixed point value, and bit slicing do extract the component parts again. His suggestion also covers the 24:8 case.

    ( And everyone else who suggested just static_cast.....what were you thinking? ;) )

提交回复
热议问题