#include <iostream>
#include <iomanip>
#include <limits>
using namespace std;

void printBitsInByte (unsigned char *byte, ostream& os) {
    // print bits from left to right
    for (int i = 7; i >= 0; --i)
        os << (int) ((*byte >> i) & (unsigned char) 1);
    os << ' ';                  // followed by a space
}

int main() {
    cout << "\nRoundoff in representing rational fraction as double";
    cout << "\n----------------------------------------------------";

    int n, d;
    cout << "\nEnter integer numerator: " << flush;
    cin >> n;
    cout << "Enter integer denominator: " << flush;
    cin >> d;
    double x = n / (double) d;

    // get address of x and pretend it points to a byte (8 bits)
    unsigned char *byte = (unsigned char *) &x;
    cout << "\nThe bit representation of " << n << "/" << d << " ";
    cout << "assuming a Big Endian computer is:\n   ";
    for (int i = 0; i < 8; i++)
        printBitsInByte(byte + i, cout);
    cout << "\nand, assuming a Little Endian computer is:\n   ";
    for (int i = 7; i >= 0; i--)
        printBitsInByte(byte + i, cout);

    cout.precision(20);
    cout << "\n\nand its decimal value = " << x << endl;
}

