-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathNum.h
103 lines (99 loc) · 2.36 KB
/
Num.h
1
2
3
4
5
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
#ifndef FIXIE_NUM_H
#define FIXIE_NUM_H
#include <math.h>
#include <stdint.h>
#include <assert.h>
#include "Config.h"
namespace Fixie {
using namespace Config;
class Num {
public:
int32_t raw = 0;
Num() { }
Num(int32_t x) {
raw = x << fractionBits;
}
Num(double x) {
raw = round(x * (1 << fractionBits));
}
Num& operator+=(const Num &rhs) {
raw += rhs.raw;
return *this;
}
Num& operator-=(const Num &rhs) {
raw -= rhs.raw;
return *this;
}
Num& operator/=(const Num &rhs) {
assert(rhs.raw != 0);
const int32_t resultNegative = ((raw ^ rhs.raw) & 0x80000000) >> 31;
const int32_t sign = resultNegative*-2+1;
int64_t temp = static_cast<int64_t>(raw) << fractionBits;
temp += rhs.raw/2*sign;
raw = temp / rhs.raw;
return *this;
}
Num& operator*=(const Num &rhs) {
raw = (static_cast<int64_t>(raw) * rhs.raw) >> fractionBits;
return *this;
}
Num operator+(const Num &other) const {
Num result = *this;
result += other;
return result;
}
Num operator-(const Num &other) const {
Num result = *this;
result -= other;
return result;
}
Num operator*(const Num &other) const {
Num result = *this;
result *= other;
return result;
}
Num operator/(const Num &other) const {
Num result = *this;
result /= other;
return result;
}
Num operator%(Num rhs) {
int32_t a = *this;
int32_t b = rhs;
return a % b;
}
bool operator==(const Num &other) {
return raw == other.raw;
}
bool operator!=(const Num &other) {
return !(*this == other);
}
bool operator<(const Num &other) {
return raw < other.raw;
}
bool operator<=(const Num &other) {
return raw <= other.raw;
}
bool operator>(const Num &other) {
return raw > other.raw;
}
bool operator>=(const Num &other) {
return raw >= other.raw;
}
operator float() const {
return static_cast<float>(raw) / (1 << fractionBits);
}
operator double() const {
return static_cast<double>(raw) / (1 << fractionBits);
}
operator int32_t() const {
return raw / (1 << fractionBits);
}
static Num createByRaw(int32_t raw) {
Num n;
n.raw = raw;
return n;
}
};
}
#endif