feat(ex01): it works

This commit is contained in:
Khaïs COLIN 2025-05-14 13:43:07 +02:00
parent baadd5bddc
commit fce90b9a43
Signed by: logistic-bot
SSH key fingerprint: SHA256:RlpiqKeXpcPFZZ4y9Ou4xi2M8OhRJovIwDlbCaMsuAo
5 changed files with 163 additions and 0 deletions

70
ex01/Fixed.cpp Normal file
View file

@ -0,0 +1,70 @@
#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;
}