Files
42_INT_09_piscine_cpp/d02/ex01/Fixed.cpp
2022-03-14 17:42:07 +01:00

111 lines
2.7 KiB
C++

#include "Fixed.hpp"
#include "printBits.cpp"
/*
* statics variables initialisation
*
* for MAX integer :
* 00000000 01111111 11111111 11111111 ( 8388607) (-1U >> (this->_frac + 1))
* <= ... >=
* 11111111 10000000 00000000 00000000 (-8388608) ~MAX
*
*/
int const Fixed::_frac = 8;
int const Fixed::_max = -1U >> (_frac + 1);
int const Fixed::_min = ~_max;
/*
* default constructor / copy constructor / destructor
*/
Fixed::Fixed() : _value(0) {
std::cout << "Default constructor called" << '\n';
return;
}
Fixed::Fixed(Fixed const & src) {
std::cout << "Copy constructor called" << '\n';
*this = src;
return;
}
Fixed::~Fixed( void ) {
std::cout << "Destructor called" << '\n';
return;
}
/*
* int and float constructors
*/
Fixed::Fixed(int integer) {
std::cout << "Int constructor called" << '\n';
if (integer < Fixed::_min || integer > Fixed::_max)
std::cout << "error: integer out of range" << '\n';
else
this->_value = integer << Fixed::_frac;
}
Fixed::Fixed(float const floater) {
std::cout << "Float constructor called" << '\n';
if (floater < Fixed::_min || floater > Fixed::_max)
std::cout << "error: float out of range" << '\n';
else
this->_value = roundf(floater * (1 << Fixed::_frac));
// this->_value = *((int *)&floater); // access float adress content as int
// int sign = this->_value & (1 << 31); // extract sign
// int exponent = ((unsigned int)(this->_value << 1) >> 24) - 127; // extract exponent
// int integer = (this->_value << 8) | (1 << 31); // add left 1
// integer = (unsigned int)integer >> (31 - this->_frac - exponent);// align to right
// if (sign != 0)
// integer = (~integer + 1); // reverse negatif
// integer = (integer << (30 - this->_frac - exponent)) | sign; // add sign
// integer >>= (30 - this->_frac - exponent); // align right
// std::cout << "integer : " << printBitsInt(integer) << " (" << integer << ")\n";
}
/*
* assignement operator
*/
Fixed & Fixed::operator=( Fixed const & rhs ) {
std::cout << "Copy assignment operator called" << '\n';
if ( this != &rhs )
this->_value = rhs.getRawBits();
return *this;
}
/*
* functions that returns _value
*/
int Fixed::getRawBits( void ) const {
return this->_value;
}
void Fixed::setRawBits( int const raw ) {
this->_value = raw;
}
int Fixed::toInt( void ) const {
return (this->_value >> Fixed::_frac);
}
float Fixed::toFloat( void ) const {
return ((float)this->_value / (float)(1 << Fixed::_frac));
}
/*
* overload "<<" -> output fixed point in float representation
*/
std::ostream & operator<<(std::ostream & o, Fixed const & rhs)
{
o << rhs.toFloat();
return (o);
}