/ ex00 / main.cpp
main.cpp
 1  #include "Fixed.hpp"
 2  #include <iostream>
 3  
 4  // Helper to print raw fixed-point internals
 5  static void printRaw(const Fixed &obj, const char *name) {
 6    int raw = obj.getRawBits();
 7    unsigned int uraw = static_cast<unsigned int>(raw);
 8    int fb = Fixed::getFractionalBits();
 9    int frac_raw = raw & ((1 << fb) - 1);
10    std::cout << name << " raw: " << raw << " (hex 0x" << std::hex << uraw
11              << std::dec << ")";
12    std::cout << ", fractional raw: " << frac_raw << " (binary ";
13    for (int i = fb - 1; i >= 0; --i)
14      std::cout << ((frac_raw >> i) & 1);
15    std::cout << ") -> " << static_cast<float>(frac_raw) / (1 << fb) << std::endl
16              << std::endl;
17  }
18  
19  Fixed add(Fixed x, Fixed y) { return Fixed(x.toFloat() + y.toFloat()); }
20  
21  int main() {
22    std::cout << "=== Fixed Class Demo ===" << std::endl;
23  
24    // Default constructor
25    Fixed a;
26    std::cout << "a: " << a << std::endl;
27    printRaw(a, "a");
28  
29    // Int constructor
30    Fixed b(10);
31    std::cout << "b: " << b << " (from int 10)" << std::endl;
32    printRaw(b, "b");
33  
34    // Float constructor
35    Fixed c(42.42f);
36    std::cout << "c: " << c << " (from float 42.42)" << std::endl;
37    printRaw(c, "c");
38  
39    // Copy constructor
40    Fixed d = b;
41    std::cout << "d: " << d << " (copy of b)" << std::endl;
42    printRaw(d, "d");
43  
44    // Assignment operator
45    a = c;
46    std::cout << "a after assignment from c: " << a << std::endl;
47    printRaw(a, "a (after assignment)");
48  
49    // Arithmetic demo using copy constructors
50    Fixed result = add(b, c);
51    std::cout << "b + c = " << result << std::endl;
52    printRaw(result, "b + c");
53  
54    // Explicit toFloat conversion
55    std::cout << "c as float: " << c.toFloat() << std::endl;
56    printRaw(c, "c (final)");
57  
58    std::cout << "=== End of Demo ===" << std::endl;
59  
60    return 0;
61  }