Binary Addition

23:55 0 Comments A+ a-

Problem:
Add two Binary Numbers...
Solution:
# include <iostream>
using namespace std;
int toDec(int binary)
{
int x = 0, a = 0, y = 0;
while (binary != 0)
{
x = binary % 10;
binary = binary / 10;
y = x*pow(2, a) + y;
a++;
}
return y;
}
int main()
{
int x;
int y;
int a[10];
int b[10];
int result[20];
cout << "Please Enter 1st Binary Number : ";
cin >> x;
cout << "Please Enter 2nd Binary Number : ";
cin >> y;
int x1 = toDec(x);
int x2 = toDec(y);
int x3 = x1 + x2;
for (int j = 0; j < 10; j++)
{
a[j] = x % 10;
b[j] = y % 10;
x = x / 10;
y = y / 10;
}

for (int i = 0; i <10; i++)
{
if (a[i] + b[i]  == 0)
{
result[i] = 0;
}
else if (a[i] + b[i]  == 1)
{
result[i] = 1;
}
else if (a[i] + b[i] == 2)
{
result[i] = 0;
a[i + 1]++;
}
else if (a[i] + b[i] == 3)
{
result[i] = 1;
a[i + 1]++;

}
else if (a[i] + b[i]  == 4)
{
result[i] = 0;
a[i + 2]++;
}
}

int addResult = 0;
for (int k= 0; k < 10; k++)
{
addResult = addResult * 10 + result[k];
}
while (toDec(addResult) != x3)
{
addResult = addResult / 10;
}
cout <<"The Sum of 2 Binary Numbers is : "<< addResult << endl;

system("pause");
return 0;

}