feat(ex01): it works
This commit is contained in:
parent
baadd5bddc
commit
fce90b9a43
5 changed files with 163 additions and 0 deletions
70
ex01/Fixed.cpp
Normal file
70
ex01/Fixed.cpp
Normal 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;
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue