Advertisement
Guest User

Untitled

a guest
Jul 28th, 2017
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.09 KB | None | 0 0
  1. #include <iostream>
  2. #include <cmath>
  3.  
  4. // Fixed point arithmetic class template backed by int
  5. template <int decimal_bits>
  6. class Fixed final
  7. {
  8. public:
  9. // ctors
  10. Fixed() {};
  11. constexpr Fixed(int data):
  12. data(data)
  13. { };
  14. constexpr Fixed(const Fixed<decimal_bits> &other):
  15. data(other.data)
  16. { };
  17.  
  18. // named converting ctors
  19. constexpr static Fixed<decimal_bits> fromInt(int i)
  20. {
  21. return {i << decimal_bits};
  22. }
  23. constexpr static Fixed<decimal_bits> fromFloat(float f)
  24. {
  25. return {(int)((f) * (float)(1<<(decimal_bits))) };
  26. }
  27.  
  28. // casts
  29. constexpr explicit operator int() const
  30. {
  31. return data >> decimal_bits;
  32. };
  33. constexpr explicit operator float() const
  34. {
  35. return (((float)(data)) / (float)(1<<(decimal_bits)));
  36. };
  37.  
  38. // arithmetic operators
  39. constexpr Fixed<decimal_bits> operator+(const Fixed<decimal_bits> &other) const
  40. {
  41. return {data + other.data};
  42. }
  43. constexpr Fixed<decimal_bits> operator-() const
  44. {
  45. return {-data};
  46. }
  47. constexpr Fixed<decimal_bits> operator-(const Fixed<decimal_bits> &other) const
  48. {
  49. return {data - other.data};
  50. }
  51. constexpr Fixed<decimal_bits> operator*(const Fixed<decimal_bits> &other) const
  52. {
  53. return { (data >> (decimal_bits >> 1))
  54. * (other.data >> ((decimal_bits >> 1) + (decimal_bits & 1)))};
  55. }
  56.  
  57. // private:
  58. int data;
  59. };
  60.  
  61. constexpr Fixed<16> operator ""_Q(unsigned long long int i)
  62. {
  63. return Fixed<16>::fromInt(i);
  64. }
  65.  
  66. constexpr Fixed<16> operator ""_Q(long double d)
  67. {
  68. return Fixed<16>::fromFloat(d);
  69. }
  70.  
  71. int main(int argc, char **argv)
  72. {
  73. constexpr static Fixed<16> a = 5.0_Q;
  74. constexpr static Fixed<16> b = 2.5_Q;
  75. constexpr static Fixed<16> c = a * b;
  76. std::cout << (float) c << std::endl;
  77. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement