Develop a SIMPLE program in C that first asks the user to in
Develop a SIMPLE program in C++:
that first asks the user to input a signed number, for example 48, then converts it to binary number by using Two’s Complement regulations. Do the same for the second inputted number, e.g., -17. Then compute the summation of these two numbers, output the results in binary format first, then if there is an overflow, display error message; otherwise, convert the result to decimal value and show it on the screen, e.g., 48 + (-17) = 31.
Note
that there is no limit to the number of bits the program can handle. For convenience, the program can assume it is for eight-bit binary numbers. Also assume all inputs are valid. CANNOT use library functions in the header file to implement it.
Solution
#include <iostream>
#include <string>
#include <cmath>
using namespace std;
string DecimalToBinary(unsigned int dec){
char binary[33] = {0};
int ix = 32; // subscript of current character
do{
binary[--ix] = \'0\' + dec % 2;
dec /= 2;
} while (dec);
return (binary+ix); // ix is offset into char array where answer begins
}
int convertBinaryToDecimal(int* n){
int decimalNumber = 0, i = 32, j=0, remainder;
while (i>0){
remainder = n[i];
decimalNumber += remainder*pow(2,j);
++j;
--i;
}
return decimalNumber;
}
int* add(string num1, string num2, int* sum){
int a[32];
int b[32];
int result[32];//, sum[32];
int carry = 0;
for (int k=0; k<32; k++){
a[k] = (int)num1[k];
b[k] = (int)num2[k];
}
for(int i=0; i<4; i++){
if(a[i]+b[i]+carry==3){
result[i]=1;
carry=1;
}
if(a[i]+b[i]+carry==2){
result[i]=0;
carry=1;
}
if(a[i]+b[i]+carry==1){
result[i]=1;
carry=0;
}
if(a[i]+b[i]+carry==0){
result[i]=0;
carry=0;
}
}
result[32]=carry;
for(int j=32; j>=0; j--){
sum[32-j]<<result[j];
}
}
int main(){
int decimal;
int num1, num2;
string a, b;
int c[32];
cout << \"Enter decimal Number: \";
cin >> num1;
cout << \"\ Enter another decimal Number: \";
cin >> num2;
a = DecimalToBinary(num1);
b = DecimalToBinary(num2);
add(a, b, c);
cout<<convertBinaryToDecimal(c);
return 0;
}

