<p>I need to speed up a program for the Nintendo DS which doesn't have an FPU, so I need to change floating-point math (which is emulated and slow) to fixed-point.</p>

<p>How I started was I changed floats to ints and whenever I needed to convert them, I used <strong>x>>8</strong> to convert the fixed-point variable x to the actual number and <strong>x&lt;&lt;8</strong> to convert to fixed-point. Soon I found out it was impossible to keep track of what needed to be converted and I also realized it would be difficult to change the precision of the numbers (8 in this case.)</p>

<p>My question is, how should I make this easier and still fast? Should I make a FixedPoint class, or just a FixedPoint8 typedef or struct with some functions/macros to convert them, or something else? Should I put something in the variable name to show it's fixed-point?</p>

[{'answer_id': 79700, 'author': 'jfm3', 'author_id': 11138, 'author_profile': 'https://Stackoverflow.com/users/11138', 'pm_score': 0, 'selected': False, 'text': "<p>Whichever way you decide to go (I'd lean toward a typedef and some CPP macros for converting), you will need to be careful to convert back and forth with some discipline.</p>\n\n<p>You might find that you never need to convert back and forth.  Just imagine everything in the whole system is x256.</p>\n"}, {'answer_id': 79701, 'author': 'Bart', 'author_id': 4343, 'author_profile': 'https://Stackoverflow.com/users/4343', 'pm_score': 3, 'selected': False, 'text': '<p>Changing fixed point representations is commonly called \'scaling\'.</p>\n\n<p>If you can do this with a class with no performance penalty, then that\'s the way to go.  It depends heavily on the compiler and how it inlines.  If there is a performance penalty using classes, then you need a more traditional C-style approach.  The OOP approach will give you compiler-enforced type safety which the traditional implementation only approximates.</p>\n\n<p>@cibyr has a good OOP implementation.  Now for the more traditional one.</p>\n\n<p>To keep track of which variables are scaled, you need to use a consistent convention.  Make a notation at the end of each variable name to indicate whether the value is scaled or not, and write macros SCALE() and UNSCALE() that expand to x>>8 and x&lt;&lt;8.  </p>\n\n<pre><code>#define SCALE(x) (x&gt;&gt;8)\n#define UNSCALE(x) (x&lt;&lt;8)\n\nxPositionUnscaled = UNSCALE(10);\nxPositionScaled = SCALE(xPositionUnscaled);\n</code></pre>\n\n<p>It may seem like extra work to use so much notation, but notice how you can tell at a glance that any line is correct without looking at other lines. For example:</p>\n\n<pre><code>xPositionScaled = SCALE(xPositionScaled);\n</code></pre>\n\n<p>is obviously wrong, by inspection.</p>\n\n<p>This is a variation of the <strong>Apps Hungarian</strong> idea that <a href="http://www.joelonsoftware.com/articles/Wrong.html" rel="nofollow noreferrer">Joel mentions in this post</a>.</p>\n'}, {'answer_id': 79717, 'author': 'Ana Betts', 'author_id': 5728, 'author_profile': 'https://Stackoverflow.com/users/5728', 'pm_score': 3, 'selected': False, 'text': '<p>The original version of <a href="https://rads.stackoverflow.com/amzn/click/com/0672305070" rel="nofollow noreferrer" rel="nofollow noreferrer">Tricks of the Game Programming Gurus</a> has an entire chapter on implementing fixed-point math.</p>\n'}, {'answer_id': 79735, 'author': 'Antti Kissaniemi', 'author_id': 2948, 'author_profile': 'https://Stackoverflow.com/users/2948', 'pm_score': 5, 'selected': False, 'text': '<p>In modern C++ implementations, there will be no performance penalty for using simple and lean abstractions, such as concrete classes. Fixed-point computation is <strong>precisely</strong> the place where using a properly engineered class will save you from lots of bugs.</p>\n\n<p>Therefore, <strong>you should write a FixedPoint8 class</strong>. Test and debug it thoroughly. If you have to convince yourself of its performance as compared to using plain integers, measure it.</p>\n\n<p>It will save you from many a trouble by moving the complexity of fixed-point calculation to a single place.</p>\n\n<p>If you like, you can further increase the utility of your class by making it a template and replacing the old <code>FixedPoint8</code> with, say, <code>typedef FixedPoint&lt;short, 8&gt; FixedPoint8;</code> But on your target architecture this is not probably necessary, so avoid the complexity of templates at first.</p>\n\n<p>There is probably a good fixed point class somewhere in the internet - I\'d start looking from the <a href="http://www.boost.org/" rel="noreferrer">Boost</a> libraries.</p>\n'}, {'answer_id': 79763, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': '<pre><code>template &lt;int precision = 8&gt; class FixedPoint {\nprivate:\n    int val_;\npublic:\n    inline FixedPoint(int val) : val_ (val &lt;&lt; precision) {};\n    inline operator int() { return val_ &gt;&gt; precision; }\n    // Other operators...\n};\n</code></pre>\n'}, {'answer_id': 79771, 'author': 'paxdiablo', 'author_id': 14860, 'author_profile': 'https://Stackoverflow.com/users/14860', 'pm_score': 3, 'selected': False, 'text': "<p>I wouldn't use floating point at all on a CPU without special hardware for handling it.  My advice is to treat ALL numbers as integers scaled to a specific factor.  For example, all monetary values are in cents as integers rather than dollars as floats.  For example, 0.72 is represented as the integer 72.</p>\n\n<p>Addition and subtraction are then a very simple integer operation such as (0.72 + 1 becomes 72 + 100 becomes 172 becomes 1.72).</p>\n\n<p>Multiplication is slightly more complex as it needs an integer multiply followed by a scale back such as (0.72 * 2 becomes 72 * 200 becomes 14400 becomes 144 (scaleback) becomes 1.44).</p>\n\n<p>That may require special functions for performing more complex math (sine, cosine, etc) but even those can be sped up by using lookup tables.  Example: since you're using fixed-2 representation, there's only 100 values in the range (0.0,1] (0-99) and sin/cos repeat outside this range so you only need a 100-integer lookup table.</p>\n\n<p>Cheers,\nPax.</p>\n"}, {'answer_id': 79784, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 3, 'selected': False, 'text': '<p>Does your floating point code actually make use of the decimal point?  If so:</p>\n\n<p>First you have to read Randy Yates\'s paper on Intro to Fixed Point Math:\n<a href="http://www.digitalsignallabs.com/fp.pdf" rel="noreferrer">http://www.digitalsignallabs.com/fp.pdf</a></p>\n\n<p>Then you need to do "profiling" on your floating point code to figure out the appropriate range of fixed-point values required at "critical" points in your code, e.g. U(5,3) = 5 bits to the left, 3 bits to the right, unsigned.</p>\n\n<p>At this point, you can apply the arithmetic rules in the paper mentioned above; the rules specify how to interpret the bits which result from arithmetic operations.  You can write macros or functions to perform the operations.</p>\n\n<p>It\'s handy to keep the floating point version around, in order to compare the floating point vs fixed point results.</p>\n'}, {'answer_id': 79942, 'author': 'Evan Teran', 'author_id': 13430, 'author_profile': 'https://Stackoverflow.com/users/13430', 'pm_score': 6, 'selected': False, 'text': '<p>You can try my fixed point class (Latest available @ <a href="https://github.com/eteran/cpp-utilities" rel="noreferrer">https://github.com/eteran/cpp-utilities</a>)</p>\n\n<pre><code>// From: https://github.com/eteran/cpp-utilities/edit/master/Fixed.h\n// See also: http://stackoverflow.com/questions/79677/whats-the-best-way-to-do-fixed-point-math\n/*\n * The MIT License (MIT)\n * \n * Copyright (c) 2015 Evan Teran\n * \n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the "Software"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n * \n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n * \n * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\n#ifndef FIXED_H_\n#define FIXED_H_\n\n#include &lt;ostream&gt;\n#include &lt;exception&gt;\n#include &lt;cstddef&gt; // for size_t\n#include &lt;cstdint&gt;\n#include &lt;type_traits&gt;\n\n#include &lt;boost/operators.hpp&gt;\n\nnamespace numeric {\n\ntemplate &lt;size_t I, size_t F&gt;\nclass Fixed;\n\nnamespace detail {\n\n// helper templates to make magic with types :)\n// these allow us to determine resonable types from\n// a desired size, they also let us infer the next largest type\n// from a type which is nice for the division op\ntemplate &lt;size_t T&gt;\nstruct type_from_size {\n    static const bool is_specialized = false;\n    typedef void      value_type;\n};\n\n#if defined(__GNUC__) &amp;&amp; defined(__x86_64__)\ntemplate &lt;&gt;\nstruct type_from_size&lt;128&gt; {\n    static const bool           is_specialized = true;\n    static const size_t         size = 128;\n    typedef __int128            value_type;\n    typedef unsigned __int128   unsigned_type;\n    typedef __int128            signed_type;\n    typedef type_from_size&lt;256&gt; next_size;\n};\n#endif\n\ntemplate &lt;&gt;\nstruct type_from_size&lt;64&gt; {\n    static const bool           is_specialized = true;\n    static const size_t         size = 64;\n    typedef int64_t             value_type;\n    typedef uint64_t            unsigned_type;\n    typedef int64_t             signed_type;\n    typedef type_from_size&lt;128&gt; next_size;\n};\n\ntemplate &lt;&gt;\nstruct type_from_size&lt;32&gt; {\n    static const bool          is_specialized = true;\n    static const size_t        size = 32;\n    typedef int32_t            value_type;\n    typedef uint32_t           unsigned_type;\n    typedef int32_t            signed_type;\n    typedef type_from_size&lt;64&gt; next_size;\n};\n\ntemplate &lt;&gt;\nstruct type_from_size&lt;16&gt; {\n    static const bool          is_specialized = true;\n    static const size_t        size = 16;\n    typedef int16_t            value_type;\n    typedef uint16_t           unsigned_type;\n    typedef int16_t            signed_type;\n    typedef type_from_size&lt;32&gt; next_size;\n};\n\ntemplate &lt;&gt;\nstruct type_from_size&lt;8&gt; {\n    static const bool          is_specialized = true;\n    static const size_t        size = 8;\n    typedef int8_t             value_type;\n    typedef uint8_t            unsigned_type;\n    typedef int8_t             signed_type;\n    typedef type_from_size&lt;16&gt; next_size;\n};\n\n// this is to assist in adding support for non-native base\n// types (for adding big-int support), this should be fine\n// unless your bit-int class doesn\'t nicely support casting\ntemplate &lt;class B, class N&gt;\nB next_to_base(const N&amp; rhs) {\n    return static_cast&lt;B&gt;(rhs);\n}\n\nstruct divide_by_zero : std::exception {\n};\n\ntemplate &lt;size_t I, size_t F&gt;\nFixed&lt;I,F&gt; divide(const Fixed&lt;I,F&gt; &amp;numerator, const Fixed&lt;I,F&gt; &amp;denominator, Fixed&lt;I,F&gt; &amp;remainder, typename std::enable_if&lt;type_from_size&lt;I+F&gt;::next_size::is_specialized&gt;::type* = 0) {\n\n    typedef typename Fixed&lt;I,F&gt;::next_type next_type;\n    typedef typename Fixed&lt;I,F&gt;::base_type base_type;\n    static const size_t fractional_bits = Fixed&lt;I,F&gt;::fractional_bits;\n\n    next_type t(numerator.to_raw());\n    t &lt;&lt;= fractional_bits;\n\n    Fixed&lt;I,F&gt; quotient;\n\n    quotient  = Fixed&lt;I,F&gt;::from_base(next_to_base&lt;base_type&gt;(t / denominator.to_raw()));\n    remainder = Fixed&lt;I,F&gt;::from_base(next_to_base&lt;base_type&gt;(t % denominator.to_raw()));\n\n    return quotient;\n}\n\ntemplate &lt;size_t I, size_t F&gt;\nFixed&lt;I,F&gt; divide(Fixed&lt;I,F&gt; numerator, Fixed&lt;I,F&gt; denominator, Fixed&lt;I,F&gt; &amp;remainder, typename std::enable_if&lt;!type_from_size&lt;I+F&gt;::next_size::is_specialized&gt;::type* = 0) {\n\n    // NOTE(eteran): division is broken for large types :-(\n    // especially when dealing with negative quantities\n\n    typedef typename Fixed&lt;I,F&gt;::base_type     base_type;\n    typedef typename Fixed&lt;I,F&gt;::unsigned_type unsigned_type;\n\n    static const int bits = Fixed&lt;I,F&gt;::total_bits;\n\n    if(denominator == 0) {\n        throw divide_by_zero();\n    } else {\n\n        int sign = 0;\n\n        Fixed&lt;I,F&gt; quotient;\n\n        if(numerator &lt; 0) {\n            sign ^= 1;\n            numerator = -numerator;\n        }\n\n        if(denominator &lt; 0) {\n            sign ^= 1;\n            denominator = -denominator;\n        }\n\n            base_type n      = numerator.to_raw();\n            base_type d      = denominator.to_raw();\n            base_type x      = 1;\n            base_type answer = 0;\n\n            // egyptian division algorithm\n            while((n &gt;= d) &amp;&amp; (((d &gt;&gt; (bits - 1)) &amp; 1) == 0)) {\n                x &lt;&lt;= 1;\n                d &lt;&lt;= 1;\n            }\n\n            while(x != 0) {\n                if(n &gt;= d) {\n                    n      -= d;\n                    answer += x;\n                }\n\n                x &gt;&gt;= 1;\n                d &gt;&gt;= 1;\n            }\n\n            unsigned_type l1 = n;\n            unsigned_type l2 = denominator.to_raw();\n\n            // calculate the lower bits (needs to be unsigned)\n            // unfortunately for many fractions this overflows the type still :-/\n            const unsigned_type lo = (static_cast&lt;unsigned_type&gt;(n) &lt;&lt; F) / denominator.to_raw();\n\n            quotient  = Fixed&lt;I,F&gt;::from_base((answer &lt;&lt; F) | lo);\n            remainder = n;\n\n        if(sign) {\n            quotient = -quotient;\n        }\n\n        return quotient;\n    }\n}\n\n// this is the usual implementation of multiplication\ntemplate &lt;size_t I, size_t F&gt;\nvoid multiply(const Fixed&lt;I,F&gt; &amp;lhs, const Fixed&lt;I,F&gt; &amp;rhs, Fixed&lt;I,F&gt; &amp;result, typename std::enable_if&lt;type_from_size&lt;I+F&gt;::next_size::is_specialized&gt;::type* = 0) {\n\n    typedef typename Fixed&lt;I,F&gt;::next_type next_type;\n    typedef typename Fixed&lt;I,F&gt;::base_type base_type;\n\n    static const size_t fractional_bits = Fixed&lt;I,F&gt;::fractional_bits;\n\n    next_type t(static_cast&lt;next_type&gt;(lhs.to_raw()) * static_cast&lt;next_type&gt;(rhs.to_raw()));\n    t &gt;&gt;= fractional_bits;\n    result = Fixed&lt;I,F&gt;::from_base(next_to_base&lt;base_type&gt;(t));\n}\n\n// this is the fall back version we use when we don\'t have a next size\n// it is slightly slower, but is more robust since it doesn\'t\n// require and upgraded type\ntemplate &lt;size_t I, size_t F&gt;\nvoid multiply(const Fixed&lt;I,F&gt; &amp;lhs, const Fixed&lt;I,F&gt; &amp;rhs, Fixed&lt;I,F&gt; &amp;result, typename std::enable_if&lt;!type_from_size&lt;I+F&gt;::next_size::is_specialized&gt;::type* = 0) {\n\n    typedef typename Fixed&lt;I,F&gt;::base_type base_type;\n\n    static const size_t fractional_bits = Fixed&lt;I,F&gt;::fractional_bits;\n    static const size_t integer_mask    = Fixed&lt;I,F&gt;::integer_mask;\n    static const size_t fractional_mask = Fixed&lt;I,F&gt;::fractional_mask;\n\n    // more costly but doesn\'t need a larger type\n    const base_type a_hi = (lhs.to_raw() &amp; integer_mask) &gt;&gt; fractional_bits;\n    const base_type b_hi = (rhs.to_raw() &amp; integer_mask) &gt;&gt; fractional_bits;\n    const base_type a_lo = (lhs.to_raw() &amp; fractional_mask);\n    const base_type b_lo = (rhs.to_raw() &amp; fractional_mask);\n\n    const base_type x1 = a_hi * b_hi;\n    const base_type x2 = a_hi * b_lo;\n    const base_type x3 = a_lo * b_hi;\n    const base_type x4 = a_lo * b_lo;\n\n    result = Fixed&lt;I,F&gt;::from_base((x1 &lt;&lt; fractional_bits) + (x3 + x2) + (x4 &gt;&gt; fractional_bits));\n\n}\n}\n\n/*\n * inheriting from boost::operators enables us to be a drop in replacement for base types\n * without having to specify all the different versions of operators manually\n */\ntemplate &lt;size_t I, size_t F&gt;\nclass Fixed : boost::operators&lt;Fixed&lt;I,F&gt;&gt; {\n    static_assert(detail::type_from_size&lt;I + F&gt;::is_specialized, "invalid combination of sizes");\n\npublic:\n    static const size_t fractional_bits = F;\n    static const size_t integer_bits    = I;\n    static const size_t total_bits      = I + F;\n\n    typedef detail::type_from_size&lt;total_bits&gt;             base_type_info;\n\n    typedef typename base_type_info::value_type            base_type;\n    typedef typename base_type_info::next_size::value_type next_type;\n    typedef typename base_type_info::unsigned_type         unsigned_type;\n\npublic:\n    static const size_t base_size          = base_type_info::size;\n    static const base_type fractional_mask = ~((~base_type(0)) &lt;&lt; fractional_bits);\n    static const base_type integer_mask    = ~fractional_mask;\n\npublic:\n    static const base_type one = base_type(1) &lt;&lt; fractional_bits;\n\npublic: // constructors\n    Fixed() : data_(0) {\n    }\n\n    Fixed(long n) : data_(base_type(n) &lt;&lt; fractional_bits) {\n        // TODO(eteran): assert in range!\n    }\n\n    Fixed(unsigned long n) : data_(base_type(n) &lt;&lt; fractional_bits) {\n        // TODO(eteran): assert in range!\n    }\n\n    Fixed(int n) : data_(base_type(n) &lt;&lt; fractional_bits) {\n        // TODO(eteran): assert in range!\n    }\n\n    Fixed(unsigned int n) : data_(base_type(n) &lt;&lt; fractional_bits) {\n        // TODO(eteran): assert in range!\n    }\n\n    Fixed(float n) : data_(static_cast&lt;base_type&gt;(n * one)) {\n        // TODO(eteran): assert in range!\n    }\n\n    Fixed(double n) : data_(static_cast&lt;base_type&gt;(n * one))  {\n        // TODO(eteran): assert in range!\n    }\n\n    Fixed(const Fixed &amp;o) : data_(o.data_) {\n    }\n\n    Fixed&amp; operator=(const Fixed &amp;o) {\n        data_ = o.data_;\n        return *this;\n    }\n\nprivate:\n    // this makes it simpler to create a fixed point object from\n    // a native type without scaling\n    // use "Fixed::from_base" in order to perform this.\n    struct NoScale {};\n\n    Fixed(base_type n, const NoScale &amp;) : data_(n) {\n    }\n\npublic:\n    static Fixed from_base(base_type n) {\n        return Fixed(n, NoScale());\n    }\n\npublic: // comparison operators\n    bool operator==(const Fixed &amp;o) const {\n        return data_ == o.data_;\n    }\n\n    bool operator&lt;(const Fixed &amp;o) const {\n        return data_ &lt; o.data_;\n    }\n\npublic: // unary operators\n    bool operator!() const {\n        return !data_;\n    }\n\n    Fixed operator~() const {\n        Fixed t(*this);\n        t.data_ = ~t.data_;\n        return t;\n    }\n\n    Fixed operator-() const {\n        Fixed t(*this);\n        t.data_ = -t.data_;\n        return t;\n    }\n\n    Fixed operator+() const {\n        return *this;\n    }\n\n    Fixed&amp; operator++() {\n        data_ += one;\n        return *this;\n    }\n\n    Fixed&amp; operator--() {\n        data_ -= one;\n        return *this;\n    }\n\npublic: // basic math operators\n    Fixed&amp; operator+=(const Fixed &amp;n) {\n        data_ += n.data_;\n        return *this;\n    }\n\n    Fixed&amp; operator-=(const Fixed &amp;n) {\n        data_ -= n.data_;\n        return *this;\n    }\n\n    Fixed&amp; operator&amp;=(const Fixed &amp;n) {\n        data_ &amp;= n.data_;\n        return *this;\n    }\n\n    Fixed&amp; operator|=(const Fixed &amp;n) {\n        data_ |= n.data_;\n        return *this;\n    }\n\n    Fixed&amp; operator^=(const Fixed &amp;n) {\n        data_ ^= n.data_;\n        return *this;\n    }\n\n    Fixed&amp; operator*=(const Fixed &amp;n) {\n        detail::multiply(*this, n, *this);\n        return *this;\n    }\n\n    Fixed&amp; operator/=(const Fixed &amp;n) {\n        Fixed temp;\n        *this = detail::divide(*this, n, temp);\n        return *this;\n    }\n\n    Fixed&amp; operator&gt;&gt;=(const Fixed &amp;n) {\n        data_ &gt;&gt;= n.to_int();\n        return *this;\n    }\n\n    Fixed&amp; operator&lt;&lt;=(const Fixed &amp;n) {\n        data_ &lt;&lt;= n.to_int();\n        return *this;\n    }\n\npublic: // conversion to basic types\n    int to_int() const {\n        return (data_ &amp; integer_mask) &gt;&gt; fractional_bits;\n    }\n\n    unsigned int to_uint() const {\n        return (data_ &amp; integer_mask) &gt;&gt; fractional_bits;\n    }\n\n    float to_float() const {\n        return static_cast&lt;float&gt;(data_) / Fixed::one;\n    }\n\n    double to_double() const        {\n        return static_cast&lt;double&gt;(data_) / Fixed::one;\n    }\n\n    base_type to_raw() const {\n        return data_;\n    }\n\npublic:\n    void swap(Fixed &amp;rhs) {\n        using std::swap;\n        swap(data_, rhs.data_);\n    }\n\npublic:\n    base_type data_;\n};\n\n// if we have the same fractional portion, but differing integer portions, we trivially upgrade the smaller type\ntemplate &lt;size_t I1, size_t I2, size_t F&gt;\ntypename std::conditional&lt;I1 &gt;= I2, Fixed&lt;I1,F&gt;, Fixed&lt;I2,F&gt;&gt;::type operator+(const Fixed&lt;I1,F&gt; &amp;lhs, const Fixed&lt;I2,F&gt; &amp;rhs) {\n\n    typedef typename std::conditional&lt;\n        I1 &gt;= I2,\n        Fixed&lt;I1,F&gt;,\n        Fixed&lt;I2,F&gt;\n    &gt;::type T;\n\n    const T l = T::from_base(lhs.to_raw());\n    const T r = T::from_base(rhs.to_raw());\n    return l + r;\n}\n\ntemplate &lt;size_t I1, size_t I2, size_t F&gt;\ntypename std::conditional&lt;I1 &gt;= I2, Fixed&lt;I1,F&gt;, Fixed&lt;I2,F&gt;&gt;::type operator-(const Fixed&lt;I1,F&gt; &amp;lhs, const Fixed&lt;I2,F&gt; &amp;rhs) {\n\n    typedef typename std::conditional&lt;\n        I1 &gt;= I2,\n        Fixed&lt;I1,F&gt;,\n        Fixed&lt;I2,F&gt;\n    &gt;::type T;\n\n    const T l = T::from_base(lhs.to_raw());\n    const T r = T::from_base(rhs.to_raw());\n    return l - r;\n}\n\ntemplate &lt;size_t I1, size_t I2, size_t F&gt;\ntypename std::conditional&lt;I1 &gt;= I2, Fixed&lt;I1,F&gt;, Fixed&lt;I2,F&gt;&gt;::type operator*(const Fixed&lt;I1,F&gt; &amp;lhs, const Fixed&lt;I2,F&gt; &amp;rhs) {\n\n    typedef typename std::conditional&lt;\n        I1 &gt;= I2,\n        Fixed&lt;I1,F&gt;,\n        Fixed&lt;I2,F&gt;\n    &gt;::type T;\n\n    const T l = T::from_base(lhs.to_raw());\n    const T r = T::from_base(rhs.to_raw());\n    return l * r;\n}\n\ntemplate &lt;size_t I1, size_t I2, size_t F&gt;\ntypename std::conditional&lt;I1 &gt;= I2, Fixed&lt;I1,F&gt;, Fixed&lt;I2,F&gt;&gt;::type operator/(const Fixed&lt;I1,F&gt; &amp;lhs, const Fixed&lt;I2,F&gt; &amp;rhs) {\n\n    typedef typename std::conditional&lt;\n        I1 &gt;= I2,\n        Fixed&lt;I1,F&gt;,\n        Fixed&lt;I2,F&gt;\n    &gt;::type T;\n\n    const T l = T::from_base(lhs.to_raw());\n    const T r = T::from_base(rhs.to_raw());\n    return l / r;\n}\n\ntemplate &lt;size_t I, size_t F&gt;\nstd::ostream &amp;operator&lt;&lt;(std::ostream &amp;os, const Fixed&lt;I,F&gt; &amp;f) {\n    os &lt;&lt; f.to_double();\n    return os;\n}\n\ntemplate &lt;size_t I, size_t F&gt;\nconst size_t Fixed&lt;I,F&gt;::fractional_bits;\n\ntemplate &lt;size_t I, size_t F&gt;\nconst size_t Fixed&lt;I,F&gt;::integer_bits;\n\ntemplate &lt;size_t I, size_t F&gt;\nconst size_t Fixed&lt;I,F&gt;::total_bits;\n\n}\n\n#endif\n</code></pre>\n\n<p>It is designed to be a near drop in replacement for floats/doubles and has a choose-able precision. It does make use of boost to add all the necessary math operator overloads, so you will need that as well (I believe for this it is just a header dependency, not a library dependency).</p>\n\n<p>BTW, common usage could be something like this:</p>\n\n<pre><code>using namespace numeric;\ntypedef Fixed&lt;16, 16&gt; fixed;\nfixed f;\n</code></pre>\n\n<p>The only real rule is that the number have to add up to a native size of your system such as 8, 16, 32, 64.</p>\n'}, {'answer_id': 80281, 'author': 'ryan_s', 'author_id': 13728, 'author_profile': 'https://Stackoverflow.com/users/13728', 'pm_score': 3, 'selected': False, 'text': '<p>When I first encountered fixed point numbers I found Joe Lemieux\'s article, <a href="http://www.embedded.com/columns/15201575?_requestid=65598" rel="noreferrer">Fixed-point Math in C</a>, very helpful, and it does suggest one way of representing fixed-point values.</p>\n\n<p>I didn\'t wind up using his union representation for fixed-point numbers though.  I mostly have experience with fixed-point in C, so I haven\'t had the option to use a class either.  For the most part though, I think that defining your number of fraction bits in a macro and using descriptive variable names makes this fairly easy to work with.  Also, I\'ve found that it is best to have macros or functions for multiplication and especially division, or you quickly get unreadable code.</p>\n\n<p>For example, with 24.8 values:</p>\n\n<pre><code> #include "stdio.h"\n\n/* Declarations for fixed point stuff */\n\ntypedef int int_fixed;\n\n#define FRACT_BITS 8\n#define FIXED_POINT_ONE (1 &lt;&lt; FRACT_BITS)\n#define MAKE_INT_FIXED(x) ((x) &lt;&lt; FRACT_BITS)\n#define MAKE_FLOAT_FIXED(x) ((int_fixed)((x) * FIXED_POINT_ONE))\n#define MAKE_FIXED_INT(x) ((x) &gt;&gt; FRACT_BITS)\n#define MAKE_FIXED_FLOAT(x) (((float)(x)) / FIXED_POINT_ONE)\n\n#define FIXED_MULT(x, y) ((x)*(y) &gt;&gt; FRACT_BITS)\n#define FIXED_DIV(x, y) (((x)&lt;&lt;FRACT_BITS) / (y))\n\n/* tests */\nint main()\n{\n    int_fixed fixed_x = MAKE_FLOAT_FIXED( 4.5f );\n    int_fixed fixed_y = MAKE_INT_FIXED( 2 );\n\n    int_fixed fixed_result = FIXED_MULT( fixed_x, fixed_y );\n    printf( "%.1f\\n", MAKE_FIXED_FLOAT( fixed_result ) );\n\n    fixed_result = FIXED_DIV( fixed_result, fixed_y );\n    printf( "%.1f\\n", MAKE_FIXED_FLOAT( fixed_result ) );\n\n    return 0;\n}\n</code></pre>\n\n<p>Which writes out </p>\n\n<pre>\n9.0\n4.5\n</pre>\n\n<p>Note that there are all kinds of integer overflow issues with those macros, I just wanted to keep the macros simple.  This is just a quick and dirty example of how I\'ve done this in C.  In C++ you could make something a lot cleaner using operator overloading.  Actually, you could easily make that C code a lot prettier too...</p>\n\n<p>I guess this is a long-winded way of saying: I think it\'s OK to use a typedef and macro approach.  So long as you\'re clear about what variables contain fixed point values it isn\'t too hard to maintain, but it probably won\'t be as pretty as a C++ class.  </p>\n\n<p>If I was in your position, I would try to get some profiling numbers to show where the bottlenecks are.  If there are relatively few of them then go with a typedef and macros.  If you decide that you need a global replacement of all floats with fixed-point math though, then you\'ll probably be better off with a class.</p>\n'}]
['https://Stackoverflow.com/questions/79677', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/813/']