fixed.hpp (2008B)
1 #pragma once 2 3 #include <stdint.h> 4 #include <math.h> 5 6 namespace bogaudio { 7 namespace dsp { 8 9 template<typename I, const int SCALE> 10 struct Fixed { 11 static constexpr I scale = ((I)1) << SCALE; 12 static constexpr double inverseScale = 1.0 / (double)scale; 13 typedef union { I v; } value_t; 14 value_t _v; 15 16 Fixed() { _v.v = 0; } 17 Fixed(const value_t& o) { _v.v = o.v; } 18 Fixed(const int32_t& o) { _v.v = o * scale; } 19 Fixed(const int64_t& o) { _v.v = o * scale; } 20 Fixed(const double& o) { _v.v = round(o * scale); } 21 Fixed(const float& o) { _v.v = roundf(o * scale); } 22 23 inline operator int32_t() const { return _v.v / scale; } 24 inline operator int64_t() const { return _v.v / scale; } 25 inline operator double() const { return inverseScale * (double)_v.v; } 26 inline operator float() const { return inverseScale * (float)_v.v; } 27 28 inline Fixed& operator+=(const Fixed& o) { _v.v += o._v.v; return *this; } 29 inline Fixed operator+(const Fixed& o) { return Fixed(*this) += o; } 30 inline Fixed& operator-=(const Fixed& o) { _v.v -= o._v.v; return *this; } 31 inline Fixed operator-(const Fixed& o) { return Fixed(*this) -= o; } 32 33 inline Fixed& operator+=(double o) { return *this += Fixed(o); } 34 inline Fixed operator+(double o) { return Fixed(*this) += o; } 35 inline Fixed& operator-=(double o) { return *this -= Fixed(o); } 36 inline Fixed operator-(double o) { return Fixed(*this) -= o; } 37 38 inline Fixed& operator+=(float o) { return *this += Fixed(o); } 39 inline Fixed operator+(float o) { return Fixed(*this) += o; } 40 inline Fixed& operator-=(float o) { return *this -= Fixed(o); } 41 inline Fixed operator-(float o) { return Fixed(*this) -= o; } 42 43 inline Fixed& operator+=(int o) { return *this += Fixed(o); } 44 inline Fixed operator+(int o) { return Fixed(*this) += o; } 45 inline Fixed& operator-=(int o) { return *this -= Fixed(o); } 46 inline Fixed operator-(int o) { return Fixed(*this) -= o; } 47 }; 48 49 typedef Fixed<int32_t, 16> fixed_16_16; 50 typedef Fixed<int64_t, 32> fixed_32_32; 51 52 } // namespace dsp 53 } // namespace bogaudio