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

void printBinary(int n);

int main()
{
  // Declare strings op and opWord and ints number1, number2, result.
  string op, opWord;
  int number1, number2, result;

  // Loop until ready to stop
  for (;;)
  {
    // Read op and number1; if op != "~", read number2
    cout << "Enter operator (# to stop) and operands ";
    cin >> op;
    if (op == "#") break;
    cin >> number1;
    if (op != "~")
      cin >> number2;

    switch(op[0])     // look at first character of operator op 
    {
      case '&': result = number1 & number2;
                opWord = "AND"; 
                break;
      case '|': result = number1 | number2; 
                opWord = "OR";
                break;
      case '^': result = number1 ^ number2; 
                opWord = "XOR";
                break;
      case '<': result = number1 << number2; 
                opWord = "LEFT-SHIFT";
                break;
      case '>': result = number1 >> number2; 
                opWord = "RIGHT-SHIFT";
                break;
      case '~': result = ~number1; 
                opWord = "NOT"; 
                break;
    } 

    // Output results 
    cout << "Applying the bitwise " << opWord << " operator " << op
         << " to the following:";
    cout << endl  << setw(10) << number1 << " = ";
    printBinary(number1);
    if (op != "~")
    { 
      cout << endl << setw(10) << number2 << " = ";
      printBinary(number2);
    }
    cout << "\nproduces";
    cout << endl << setw(10) << result << " = ";
    printBinary(result);
    cout << endl << endl;
  }
}

//--- Insert definition of printBinary from Problems 1 & 2 here.
void printBinary(int n)
/*-------------------------------------------------------------
  Display binary representation of n.

  Precondition:  sizeof(unsigned) and sizeof(int) are 32.  
      If this is not the case, adjust the number of 0s in mask.
  Postcondition: 32-bit representation of n has been output
  --------------------------------------------------------------*/
{
  unsigned mask = 0x80000000;
  for (int i = 0; i < 8*sizeof(int); i++)
  {
    if ((mask & n) != 0) // Note: parens needed due to priorities
      cout << '1';
    else
      cout << '0';
    // Or simply:  cout << ((mask & n) != 0 ? '1' : '0');
    mask >>= 1;
  }
}
