Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //yeo punya
- //midtermq1
- #include <iostream>
- #include <string>
- using namespace std;
- string AddBin(string num1, string num2);
- string TwosComp(string bin);
- string SubBin(string a, string b);
- int main()
- {
- string a, b,result;
- cout << "Enter 2 number: ";
- cin >> a;
- cin >> b;
- result = AddBin(a, b);
- cout << result << endl;
- result = TwosComp(a);
- cout << result << endl;
- result = SubBin(a, b);
- cout << result << endl;
- return 0;
- }
- string AddBin(string num1, string num2){
- string temp = "";
- int carry = 0;
- for (int i = num1.length() - 1; i >= 0; i--){
- if (num1.at(i) == '1'&& num2.at(i) == '1' && carry == 0){
- temp = '0' + temp;
- carry = 1;
- continue;
- }
- if (num1.at(i) == '0'&& num2.at(i) == '0' && carry == 0){
- temp = '0' + temp;
- carry = 0;
- continue;
- }
- if (num1.at(i) == '1'&& num2.at(i) == '1' && carry == 1){
- temp = '1' + temp;
- carry = 1;
- continue;
- }
- if (num1.at(i) == '0'&& num2.at(i) == '0' && carry == 1){
- temp = '1' + temp;
- carry = 0;
- continue;
- }
- if (num1.at(i) == '1'&& num2.at(i) == '0' && carry == 0){
- temp = '1' + temp;
- carry = 0;
- continue;
- }
- if (num1.at(i) == '0'&& num2.at(i) == '1' && carry == 0){
- temp = '1' + temp;
- carry = 0;
- continue;
- }
- if (num1.at(i) == '1'&& num2.at(i) == '0' && carry == 1){
- temp = '0' + temp;
- carry = 1;
- continue;
- }
- if (num1.at(i) == '0'&& num2.at(i) == '1' && carry == 1){
- temp = '0' + temp;
- carry = 1;
- continue;
- }
- }
- if (carry == 1)
- temp = '1' + temp;
- return temp;
- }
- string TwosComp(string bin){
- int len = bin.length();
- string temp = 0, one;
- for (int i = 0; i < len; i++){
- if (bin[i] == '1')
- temp = temp + '0';
- else
- temp = temp + "1";
- }
- for (int j = 0; j < len - 1; j++)
- one[j] = '0';
- one += "1";
- temp = AddBin(temp, one);
- return temp;
- }
- string SubBin(string a, string b){
- string mb = TwosComp(b);
- string temp = AddBin(a, mb);
- return temp;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement