1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
|
// NOTE: The ONLY files that should be #included for this assignment are iostream, vector, and string
// No other files should be #included
#include <iostream>
#include <vector>
#include <string>
// NOTE: The ONLY files that should be #included for this assignment are iostream, vector, and string
// No other files should be #included
using namespace std;
string addbin(string, string);
string addhex(string, string);
int main()
{
cout << "binary 1101 + 1000 = " << addbin("1101", "1000") << endl; //you should get 10101
cout << "binary 11000 + 1011 = " << addbin("11000", "1011") << endl; //you should get 100011
cout << "binary 11111111 + 1 = " << addbin("11111111", "1") << endl; //you should get 100000000
cout << "binary 101010 + 10 = " << addbin("101010", "10") << endl << endl; //you should get 101100
cout << "hexadecimal A4 + A5 = " << addhex("A4", "A5") << endl; //you should get 149
cout << "hexadecimal 2B + C = " << addhex("2B", "C") << endl; //you should get 37
cout << "hexadecimal FABC + 789 = " << addhex("FABC", "789") << endl; //you should get 10245
cout << "hexadecimal FFFFFF + FF = " << addhex("FFFFFF", "FF") << endl << endl; //you should get 10000FE
system("PAUSE");
return 0;
}
string addbin(string bin1, string bin2)
{
string result = "";
int blength1 = bin1.length();
int blength2 = bin2.length();
int bsum;
int carry = 0;
int length;
int a = 0;
int b = 0;
if (bin1 < bin2)
{
for (int i = 0; i < blength2 - blength1; i++)
bin1 = '0' + bin1;
}
if (bin2 < bin1)
{
for (int i = 0; i < blength1 - blength2; i++)
bin2 = '0' + bin2;
}
for (int i = 0; i < blength1; i++)
{
int a = int(bin1[bin1.length()]) - 48;
}
for (int i = 0; i < blength2; i++)
{
int b = int(bin2[bin2.length()]) - 48;
}
if (blength1 > blength2)
{
length = blength1;
}
else
{
length = blength2;
}
for (int i = length - 1; i >= 0; i--)
{
bsum = carry + a + b;
if (bsum == 0)
{
carry = 0;
result = "0" + result;
}
else if (bsum == 1)
{
carry = 0;
result = "1" + result;
}
else if (bsum == 2)
{
carry = 1;
result = "0" + result;
}
else if (bsum = 3)
{
carry = 1;
result = "1" + result;
}
}
if (carry = 1)
{
result = "1" + result;
}
return result;
}
string addhex(string hex1, string hex2)
{
return 0;
}
|