NTC_THERMISTOR Driver 0.1.0
API reference
Loading...
Searching...
No Matches
ntc_thermistor_math.hpp
Go to the documentation of this file.
1
15#ifndef NTC_THERMISTOR_MATH_HPP
16#define NTC_THERMISTOR_MATH_HPP
17
18#include <bit>
19#include <cstdint>
20#include <limits>
21
22namespace ntc_thermistor::detail {
23
26inline constexpr uint32_t kLnFractionBits = 16U;
29inline constexpr uint32_t kLnSteps = kLnFractionBits + 1U;
31inline constexpr uint64_t kLn2Q32 = uint64_t{2977044472U};
34inline constexpr uint64_t kTwoPow31 = uint64_t{1U} << 31U;
36inline constexpr uint64_t kTwoPow32 = uint64_t{1U} << 32U;
40inline constexpr uint64_t kFineScale = uint64_t{256U};
42inline constexpr uint64_t kMaxU64 = ~uint64_t{0U};
43
57[[nodiscard]] constexpr uint32_t Ln16(uint64_t x) noexcept {
58 if (x == 0U) {
59 return 0U;
60 }
61 const uint32_t whole = static_cast<uint32_t>(std::bit_width(x)) - 1U; // floor(log2 x), 0..63
62 // The mantissa x / 2^whole in [1, 2), as a Q31 number: [2^31, 2^32).
63 uint64_t m = (whole >= 31U) ? (x >> ((whole - 31U) & 63U)) : (x << ((31U - whole) & 63U));
64 uint32_t fraction = 0U;
65 for (uint32_t step = 0U; step < kLnSteps; ++step) {
66 m = (m * m) >> 31U; // the square, back in Q31: [2^31, 2^33)
67 fraction <<= 1U;
68 if (m >= kTwoPow32) {
69 fraction |= 1U;
70 m >>= 1U;
71 }
72 }
73 const uint32_t log2_q17 = (whole << kLnSteps) | fraction;
74 const uint64_t log2_q16 = (static_cast<uint64_t>(log2_q17) + 1U) >> 1U;
75 return static_cast<uint32_t>(((log2_q16 * kLn2Q32) + kTwoPow31) >> 32U);
76}
77
86[[nodiscard]] constexpr int64_t DivRound(int64_t a, int64_t b) noexcept {
87 if (b <= 0) {
88 return 0;
89 }
90 const int64_t half = b / 2;
91 return (a >= 0) ? ((a + half) / b) : -(((-a) + half) / b);
92}
93
101[[nodiscard]] constexpr uint64_t DivRoundU(uint64_t a, uint64_t b) noexcept {
102 if (b == 0U) {
103 return 0U;
104 }
105 const uint64_t quotient = a / b;
106 return ((a % b) >= (b - (b / 2U))) ? (quotient + 1U) : quotient;
107}
108
115[[nodiscard]] constexpr uint64_t SatMul(uint64_t a, uint64_t b) noexcept {
116 if ((a != 0U) && (b > (kMaxU64 / a))) {
117 return kMaxU64;
118 }
119 return a * b;
120}
121
128[[nodiscard]] constexpr uint64_t SatAdd(uint64_t a, uint64_t b) noexcept {
129 return (b > (kMaxU64 - a)) ? kMaxU64 : (a + b);
130}
131
140[[nodiscard]] constexpr uint64_t AbsDiff(int64_t a, int64_t b) noexcept {
141 return static_cast<uint64_t>((a >= b) ? (a - b) : (b - a));
142}
143
149[[nodiscard]] constexpr int32_t ClampToInt32(int64_t v) noexcept {
150 constexpr int64_t kLowest = std::numeric_limits<int32_t>::min();
151 constexpr int64_t kHighest = std::numeric_limits<int32_t>::max();
152 int64_t out = (v < kLowest) ? kLowest : v;
153 out = (out > kHighest) ? kHighest : out;
154 return static_cast<int32_t>(out);
155}
156
157} // namespace ntc_thermistor::detail
158
159#endif // NTC_THERMISTOR_MATH_HPP