cpp02/ex01/Fixed.cpp

71 lines
1.6 KiB
C++
Raw Normal View History

2025-05-14 13:43:07 +02:00
#include "Fixed.hpp"
#include <bitset>
#include <sstream>
const int Fixed::fracbits(8);
Fixed::Fixed() {
std::cout << "Default constructor called" << std::endl;
value = 0;
}
Fixed::Fixed(const int val) {
std::cout << "Int constructor called with " << val << std::endl;
value = val << fracbits;
}
Fixed::Fixed(const float val) {
std::cout << "Float constructor called with " << val << std::endl;
const static int factor = 1 << fracbits;
float temp = (val * factor);
if (temp >= 0)
temp += 0.5f;
else
temp -= 0.5f;
value = (int)(temp);
}
Fixed::Fixed(const Fixed &other) {
std::cout << "Copy constructor called" << std::endl;
this->value = other.value;
}
Fixed &Fixed::operator=(const Fixed &other) {
std::cout << "Copy assignment operator called" << std::endl;
this->setRawBits(other.getRawBits());
return *this;
}
Fixed::~Fixed() { std::cout << "Destructor called" << std::endl; }
int Fixed::getRawBits(void) const {
std::cout << "getRawBits member function called" << std::endl;
return value;
}
void Fixed::setRawBits(int const raw) { value = raw; }
float Fixed::toFloat(void) const {
const static int factor = 1 << fracbits;
float result = (float)value / factor;
return (result);
}
int Fixed::toInt(void) const {
int result = (value >> fracbits);
return (result);
}
std::string Fixed::toBin(void) const {
std::stringstream result;
result << std::bitset<32 - fracbits>(value >> fracbits);
result << ".";
result << std::bitset<fracbits>(value & (1 << fracbits) - 1);
return result.str();
}
std::ostream &operator<<(std::ostream &stream, const Fixed &fixed) {
stream << fixed.toFloat();
return stream;
}