cpp02/ex01/Fixed.cpp

78 lines
2.1 KiB
C++

/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* Fixed.cpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: lfirmin <lfirmin@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2025/07/02 12:25:46 by lfirmin #+# #+# */
/* Updated: 2025/07/02 12:33:48 by lfirmin ### ########.fr */
/* */
/* ************************************************************************** */
#include "Fixed.hpp"
const int Fixed::_number_fractional_bits = 8;
Fixed::Fixed() : _fixed_p_n(0)
{
std::cout << "Default constructor called\n";
}
Fixed::Fixed(const int input)
{
std::cout << "Fixed Int Constructor called" << std::endl;
this->_fixed_p_n = input << this->_number_fractional_bits;
}
Fixed::Fixed(const float input)
{
std::cout << "Fixed Float Constructor called" << std::endl;
this->_fixed_p_n = roundf(input * (1 << this->_number_fractional_bits));
}
Fixed::Fixed(const Fixed &copy)
{
std::cout << "Copy constructor called\n";
*this = copy;
}
Fixed &Fixed::operator=(const Fixed &copy)
{
std::cout << "Copy assignment constructor called\n";
setRawBits(copy.getRawBits());
return (*this);
}
Fixed::~Fixed()
{
std::cout << "Deconstructor called\n";
}
int Fixed::getRawBits(void) const
{
std::cout << "getRawBits member function called\n";
return (_fixed_p_n);
}
void Fixed::setRawBits(int const raw)
{
_fixed_p_n = raw;
}
int Fixed::toInt(void)const
{
return (this->_fixed_p_n>> this->_number_fractional_bits);
}
float Fixed::toFloat(void)const
{
return ((float)this->_fixed_p_n/ (float)(1 << this->_number_fractional_bits));
}
std::ostream &operator<<(std::ostream &o, Fixed const &fixed)
{
o << fixed.toFloat();
return (o);
}