0 day streak
cpp / expert
Snippet

Custom Fixed-Point Representation for Embedded Arithmetic

In resource-constrained environments where a Floating Point Unit (FPU) is absent, fixed-point arithmetic provides a high-performance alternative to floating-point math. This snippet uses a template parameter to define the precision (number of fractional bits) at compile-time, allowing for optimized integer arithmetic that simulates decimal values.

snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
template<int FractionalBits>
struct FixedPoint {
int32_t raw;
explicit constexpr FixedPoint(float val)
: raw(static_cast<int32_t>(val * (1 << FractionalBits) + (val >= 0 ? 0.5f : -0.5f))) {}
constexpr float toFloat() const {
return static_cast<float>(raw) / (1 << FractionalBits);
}
FixedPoint operator+(FixedPoint other) const {
FixedPoint res;
res.raw = this->raw + other.raw;
return res;
}
private:
FixedPoint() : raw(0) {}
};
Breakdown
1
template<int FractionalBits>
Defines the fixed scaling factor at compile-time for efficiency.
2
raw(static_cast<int32_t>(val * (1 << FractionalBits) ...))
Converts a float to its internal integer representation by shifting left.