summaryrefslogtreecommitdiff
path: root/src/fixed_point.cpp
blob: a39f2bc96d44599fdf97d324ef3190ce5125d920 (plain)
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
#include "fixed_point.h"
#include "fatal_error.h"
#include <limits>

fp_t fp_t::operator+(const fp_t& other) const {
    return {static_cast<std::int32_t>(static_cast<std::uint32_t>(raw) + static_cast<std::uint32_t>(other.raw))};
}

fp_t fp_t::operator-(const fp_t& other) const {
    return {static_cast<std::int32_t>(static_cast<std::uint32_t>(raw) - static_cast<std::uint32_t>(other.raw))};
}

fp_t fp_t::operator*(const fp_t& other) const {
    std::int32_t result;
    std::int64_t temp;
    temp = static_cast<std::int64_t>(raw) * static_cast<std::int64_t>(other.raw);
    temp += fp_t::K;
    result = static_cast<std::int32_t>(temp >> fp_t::Q);
    return {result};
}

fp_t fp_t::operator/(const fp_t& other) const {
    if (other.raw == 0) {
        fatal_error("fp_t: division by zero");
    }
    std::int64_t temp = static_cast<std::int64_t>(raw) << fp_t::Q;

    if ((temp >= 0 && other.raw >= 0) || (temp < 0 && other.raw < 0)) {
        temp += (other.raw / 2);
    } else {
        temp -= (other.raw / 2);
    }

    temp = temp / other.raw;

    if (temp > std::numeric_limits<std::int32_t>::max() ||
        temp < std::numeric_limits<std::int32_t>::min()) {
        fatal_error("fp_t: division overflow (raw={} / raw={})", raw, other.raw);
    }
    return {static_cast<std::int32_t>(temp)};
}

bool fp_t::operator==(const fp_t& other) const {
    return raw == other.raw;
}