C++ programming language
( x.y means multiplication of x times y )
The binary numbers should be represented as vectors (sequences) of digits. Each entry of the vector should represent a single digit the leftmost being the least significant one. For example, the vector [0, 1, 1, 0, 0, 0, 1, 1, 1] represents the binary number 111000110.
In this assignment you must not use your programming language support (nor any libraries) for arbitrary length arithmetic.
Expert Answer
Please find the code below :
#include<iostream>
#include<string>
#include<math.h>
using namespace std;
int main()
{
string x,y;
cout<<“Enter two binary numbers : “;
cin>>x>>y;
int m = x.length(); //fetching length of first binary number
int n = y.length(); //fetching length of second binary number
int a[m+n],b[n],i,j,sum,carry=0,dec=0;
int c[m+n];
for(i=0; i<m+n; i++) //loop to convert first binary string to int array
if(i<m)
a[i] = x[i]-‘0’;
else
a[i] = 0;
for(i=0; i<n; i++) //loop to convert second binary string to int array
b[i] = y[i]-‘0’;
for(i=0; i<m+n; i++) //initializing c to 0
c[i] = 0;
for(i=0; i<n; i++) //converting second binary to decimal
dec += b[i]*pow(2,i);
for(j=0; j<dec; j++) //loop to add b times a
{
for(i=0; i<m+n; i++) //adding a to c
{
sum = a[i] + c[i] + carry;
if(sum == 0)
{
c[i] = 0;
carry = 0;
}
else if(sum == 1)
{
c[i] = 1;
carry = 0;
}
else if(sum == 2)
{
c[i] = 0;
carry = 1;
}
else if(sum > 2)
{
c[i] = 1;
carry = 1;
}
}
c[i] = carry;
carry = 0;
}
for(i=0; i<m+n; i++)
cout<<c[i]<<” “;
cout<<“nChecking : n”;
dec=0;
for(i=0; i<m; i++)
dec += a[i]*pow(2,i);
cout<<“a = “<<dec<<endl;
dec=0;
for(i=0; i<n; i++)
dec += b[i]*pow(2,i);
cout<<“b = “<<dec<<endl;
dec=0;
for(i=0; i<m+n; i++)
dec += c[i]*pow(2,i);
cout<<“result = “<<dec<<endl;
return 0;
}
Output :