fix16.cpp 2.28 KB
Newer Older
louiz’'s avatar
louiz’ committed
1
2
#include "fixmath/fix16.hpp"

3
4
5
// Needed for operator<<(ostream, double)
#include <ostream>

louiz’'s avatar
louiz’ committed
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
Fix16 operator ""_fix(long double in)
{
  return Fix16(static_cast<double>(in));
}

Fix16 operator ""_fix(unsigned long long int in)
{
  return Fix16(static_cast<unsigned int>(in));
}

Fix16 operator ""_fix(const char* in, std::size_t size)
{
  return Fix16(std::string(in, size).data());
}

bool operator==(const Fix16& lhs, const Fix16& rhs)
{
  return lhs.value == rhs.value;
}

bool operator!=(const Fix16& lhs, const Fix16& rhs)
{
  return lhs.value != rhs.value;
}

bool operator<=(const Fix16& lhs, const Fix16& rhs)
{
  return lhs.value <= rhs.value;
}

bool operator<(const Fix16& lhs, const Fix16& rhs)
{
  return lhs.value < rhs.value;
}

bool operator>(const Fix16& lhs, const Fix16& rhs)
{
  return lhs.value > rhs.value;
}

bool operator>=(const Fix16& lhs, const Fix16& rhs)
{
  return lhs.value >= rhs.value;
}

Fix16 operator-(const Fix16& val)
{
  return val * -1;
}

Fix16 operator/(const Fix16& lhs, const Fix16& rhs)
{
  Fix16 res;
  res.raw() = fix16_div(lhs.value, rhs.value);
  return res;
}

Fix16 operator*(const Fix16& lhs, const Fix16& rhs)
{
  Fix16 res;
  res.raw() = fix16_mul(lhs.value, rhs.value);
  return res;
}

Fix16 operator+(const Fix16& lhs, const Fix16& rhs)
{
  Fix16 res;
  res.raw() = fix16_add(lhs.value, rhs.value);
  return res;
}

Fix16 operator-(const Fix16& lhs, const Fix16& rhs)
{
  Fix16 res;
  res.raw() = fix16_sub(lhs.value, rhs.value);
  return res;
}

Fix16 operator%(const Fix16& lhs, const Fix16& rhs)
{
  Fix16 res;
  res.raw() = fix16_mod(lhs.value, rhs.value);
  return res;
}

namespace std
{
  std::string to_string(Fix16 arg)
  {
    char buf[12];
    fix16_to_str(arg.raw(), buf, 10);
    return buf;
  }

  Fix16 sqrt(Fix16 arg)
  {
    return arg.sqrt();
  }

105
106
107
108
109
110
111
  Fix16 abs(Fix16 arg)
  {
    if (arg < 0_fix)
      return -arg;
    return arg;
  }

louiz’'s avatar
louiz’ committed
112
113
  Fix16 hypot(Fix16 x, Fix16 y)
  {
114
115
116
117
118
119
120
121
122
    static const Fix16 a = 0.96943387;
    static const Fix16 b = 0.39782473;

    x = std::abs(x);
    y = std::abs(y);
    if (x >= y)
      return a*x + b*y;
    else
      return a*y + b*x;
louiz’'s avatar
louiz’ committed
123
  }
124
125
126
127
128
129

  Fix16 floor(Fix16 val)
  {
    val.raw() = fix16_floor(val.value);
    return val;
  }
louiz’'s avatar
louiz’ committed
130
}
131
132
133
134
135
136

std::ostream& operator<<(std::ostream& os, const Fix16& rhs)
{
  return os << rhs.to_double();
}