/* * Copyright (c) Advanced Micro Devices, Inc., or its affiliates. * * SPDX-License-Identifier: MIT */ #pragma once #include template class FixedPoint { public: FixedPoint() = default; FixedPoint(float x) { fixed_point_ = static_cast(roundf(x * (1 << fractional_bits))); } operator float() const { return (static_cast(fixed_point_) / static_cast(1 << fractional_bits)); } FixedPoint operator+(FixedPoint other) const { FixedPoint res; res.fixed_point_ = fixed_point_ + other.fixed_point_; return res; } FixedPoint operator-(FixedPoint other) const { FixedPoint res; res.fixed_point_ = fixed_point_ - other.fixed_point_; return res; } FixedPoint operator*(FixedPoint other) const { constexpr auto K = 1 << (fractional_bits - 1); FixedPoint res; int32_t temp; temp = static_cast(fixed_point_) * static_cast(other.fixed_point_); temp += K; res.fixed_point_ = Sat16(temp >> fractional_bits); return res; } private: int16_t fixed_point_; int16_t Sat16(int32_t x) const { if (x > 0x7FFF) return 0x7FFF; else if (x < -0x8000) return -0x8000; else return (int16_t)x; } };