How do I implement fixed-point arithmetic in C++?

Fixed-point arithmetic is a numerical representation that can be used to represent real numbers with a fixed number of digits after the decimal point. It is particularly useful in systems where floating-point precision is limited or when performance is critical, such as in embedded systems.

In C++, fixed-point arithmetic can be implemented using integers and a scaling factor to represent the fixed number of decimal places. Below is an example of how you can implement simple fixed-point arithmetic in C++.

#include #include class FixedPoint { private: int32_t value; // Underlying integer representation static const int32_t scale = 10000; // Scale factor (4 decimal places) public: FixedPoint(int32_t v) : value(v * scale) {} FixedPoint(float v) : value(static_cast(v * scale)) {} // Addition FixedPoint operator+(const FixedPoint& other) { return FixedPoint(0, this->value + other.value); } // Subtraction FixedPoint operator-(const FixedPoint& other) { return FixedPoint(0, this->value - other.value); } // Multiplication FixedPoint operator*(const FixedPoint& other) { return FixedPoint(0, (this->value * other.value) / scale); } // Division FixedPoint operator/(const FixedPoint& other) { return FixedPoint(0, (this->value * scale) / other.value); } // Conversion to float float toFloat() const { return static_cast(value) / scale; } private: // Private constructor for internal use FixedPoint(int32_t, int32_t v) : value(v) {} }; int main() { FixedPoint a(1.2345); FixedPoint b(2.3456); FixedPoint c = a + b; std::cout << "Sum: " << c.toFloat() << std::endl; return 0; }

fixed-point arithmetic C++ programming integer representation numerical methods embedded systems