Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <cmath>
- // Fixed point arithmetic class template backed by int
- template <int decimal_bits>
- class Fixed final
- {
- public:
- // ctors
- Fixed() {};
- constexpr Fixed(int data):
- data(data)
- { };
- constexpr Fixed(const Fixed<decimal_bits> &other):
- data(other.data)
- { };
- // named converting ctors
- constexpr static Fixed<decimal_bits> fromInt(int i)
- {
- return {i << decimal_bits};
- }
- constexpr static Fixed<decimal_bits> fromFloat(float f)
- {
- return {(int)((f) * (float)(1<<(decimal_bits))) };
- }
- // casts
- constexpr explicit operator int() const
- {
- return data >> decimal_bits;
- };
- constexpr explicit operator float() const
- {
- return (((float)(data)) / (float)(1<<(decimal_bits)));
- };
- // arithmetic operators
- constexpr Fixed<decimal_bits> operator+(const Fixed<decimal_bits> &other) const
- {
- return {data + other.data};
- }
- constexpr Fixed<decimal_bits> operator-() const
- {
- return {-data};
- }
- constexpr Fixed<decimal_bits> operator-(const Fixed<decimal_bits> &other) const
- {
- return {data - other.data};
- }
- constexpr Fixed<decimal_bits> operator*(const Fixed<decimal_bits> &other) const
- {
- return { (data >> (decimal_bits >> 1))
- * (other.data >> ((decimal_bits >> 1) + (decimal_bits & 1)))};
- }
- // private:
- int data;
- };
- constexpr Fixed<16> operator ""_Q(unsigned long long int i)
- {
- return Fixed<16>::fromInt(i);
- }
- constexpr Fixed<16> operator ""_Q(long double d)
- {
- return Fixed<16>::fromFloat(d);
- }
- int main(int argc, char **argv)
- {
- constexpr static Fixed<16> a = 5.0_Q;
- constexpr static Fixed<16> b = 2.5_Q;
- constexpr static Fixed<16> c = a * b;
- std::cout << (float) c << std::endl;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement