Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * File: main.cpp
- * Author: James
- *
- * Created on November 23, 2014, 2:41 AM
- */
- #include <iostream>
- #include <string>
- #include <sstream>
- #include <cmath>
- using namespace std;
- #define nl "\n"
- /*
- * This is a bitwise calculator
- */
- bool is_number(const string& astring)
- {
- return !astring.empty() &&
- astring.find_first_not_of("-0123456789") == string::npos;
- }
- int badd (int a, int b)
- {
- int c;
- do
- {
- c = a & b;
- c = c << 1;
- b = a ^ b;
- a = b & c;
- a = a << 1;
- c = b ^ c;
- b = c & a;
- b = b << 1;
- a = c ^ a;
- } while (b != 0);
- return a;
- }
- int bsub (int a, int b)
- {
- int c = 0;
- b = badd(~b, 1); // generates the twos compliment of b
- c = badd(a, b); // adds the twos compliment to a
- return c;
- }
- int bmul (int a, int b)
- {
- int A = a;
- if ((a == 0) || (b == 0))
- return 0;
- for (int b2 = (0 - b); (abs(b) > 1) || (abs(b2) > 1); b--, b2++)
- A = badd(A, a);
- return A;
- }
- int bmod (int a, int b)
- {
- int B = b;
- while (a <= B)
- {
- B = bsub(B, a);
- }
- return B;
- }
- string bdiv (int a, int b)
- {
- int i = 0;
- stringstream conv;
- while (a >= b)
- {
- a = bsub(a, b);
- i++;
- }
- conv << i << ".";
- for (int c = 1; c <= 5; c++)
- {
- int r = 0;
- a = bmul(10, a);
- while (a >= b)
- {
- a = bsub(a, b);
- r++;
- }
- conv << r;
- }
- return conv.str();
- }
- string op_select(string op,double a,double b)
- {
- string out;
- stringstream convert;
- if (op == "+")
- convert << badd(a, b);
- if (op == "-")
- convert << bsub(a, b);
- if (op == "*")
- convert << bmul(a, b);
- if (op == "%")
- convert << bmod(a, b);
- if (op == "/")
- convert << bdiv(a, b);
- if (!(op.find_first_not_of("+-*/%") == string::npos))
- convert << "f";
- out = convert.str();
- return out;
- }
- int main()
- {
- double a, b;
- string input, result;
- cout << "enter an integer\n";
- getline (cin, input);
- if ( is_number(input) )
- stringstream(input) >> a;
- else
- {
- cout << "that's not a number...";
- return 1;
- }
- cout << "enter another integer\n";
- getline (cin, input);
- if ( is_number(input) )
- stringstream(input) >> b;
- else
- {
- cout << "that's not a number...";
- return 1;
- }
- cout << "enter a simple math operator (+,-,*,/,%)\n";
- getline (cin, input);
- result = op_select(input,a,b);
- if (result == "f")
- {
- cout << "invalid operator " << input;
- return 1;
- }
- cout << "the answer to " << a << " " << input << " " << b
- << " is: " << result << ".\n";
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement