Commit 5ee0fe4f authored by yh2920's avatar yh2920
Browse files

fixed-point operator overload with fixed-point and int

parents
int numFracBits = 8;
class FixedPoint{
public:
FixedPoint() = default;
~FixedPoint() = default;
FixedPoint(int i):
value((int)i<<numFracBits){}
FixedPoint(float f):
value((int)(f * (float)((int)1<<numFracBits))){}
FixedPoint(double f):
value((int)(f * (double)((int)1<<numFracBits))){}
//Operator overloads with fixed point
FixedPoint& operator += (FixedPoint r) {
value += r.value;
return *this;
}
FixedPoint& operator -= (FixedPoint r) {
value -= r.value;
return *this;
}
FixedPoint& operator *= (FixedPoint r) {
value = (int) (((long) value * r.value) >> numFracBits);
return *this;
}
FixedPoint operator - () const {
FixedPoint x;
x.value = -value;
return x;
}
FixedPoint operator + (const FixedPoint& r) const {
FixedPoint x = *this;
x += r;
return x;
}
FixedPoint operator - (const FixedPoint& r) const {
FixedPoint x = *this;
x -= r;
return x;
}
FixedPoint operator * (const FixedPoint& r) const {
FixedPoint x = *this;
x *= r;
return x;
}
//Binary Operator Overloads
bool operator == (const FixedPoint& r) const {
return value == r.value;
}
bool operator != (const FixedPoint &r) const{
return !(*this == r);
}
bool operator < (const FixedPoint &r) const{
return value < r.value;
}
bool operator > (const FixedPoint &r) const{
return value > r.value;
}
bool operator <= (const FixedPoint& r) const {
return value <= r.value;
}
bool operator >= (const FixedPoint& r) const {
return value >= r.value;
}
//Operator overloads with int
FixedPoint& operator += (int i) {
FixedPoint x = *this;
x += FpF(i);
return x;
}
FixedPoint& operator -= (int i) {
FixedPoint x = *this;
x -= FpF(i);
return x;
}
FixedPoint& operator *= (int i) {
value *= r;
return *this;
}
FixedPoint operator + (int i) const {
FixedPoint x = *this;
x += i;
return x;
}
FixedPoint operator - (int i) const {
FixedPoint x = *this;
x -= r;
return x;
}
FixedPoint operator * (int i) const {
FixedPoint x = *this;
x *= r;
return x;
}
//Binary Operator Overloads
bool operator == (int i) const {
return value == (int) i<<numFracBits;
}
bool operator != (int i) const{
return !(*this == r);
}
bool operator < (int i) const{
return value < (int) i<<numFracBits;
}
bool operator > (int i) const{
return value > (int) i<<numFracBits;
}
bool operator <= (int i) const {
return value <= (int) i<<numFracBits;
}
bool operator >= (int i) const {
return value >= (int) i<<numFracBits;
}
int ToInt() const {
return (int) (value >> numFracBits);
}
float ToFloat() const {
return (float) value / (float) ((int) 1 << numFracBits);
}
double ToDouble() const{
return (double) value / (float) ((int) 1 << numFracBits);
}
private:
int value;
};
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment