0
I made this code and it basically gets two numbers in binaries (no separation of spaces between bits), and Performa (at least in the values I tested) the subtraction correctly. I tried to prevent myself if one of the numbers is smaller than the other, adding a bit of zero value or more ahead of the smallest number.
However I do not get the right result for these cases.
PS: It is not necessary to worry about the signal, only about the value of the result being correct.
#include <stdlib.h>
#include <string.h>
#include <iostream>
using namespace std;
#define BUFFER_SIZE 256
int main (int argv, char* argc[]){
char num1[BUFFER_SIZE];
cin >> num1;
cin.ignore(1);
char num2[BUFFER_SIZE];
cin >> num2;
cin.ignore(1);
int length1 = strlen(num1);
int length2 = strlen(num2);
int length;
if(length1 > length2){
length = length1;
int diference = length1 - length2;
for(int i=length2; i>=0;i--){
num2[i+diference] = num1[i];
}
//You must collect the garbage
for(int i=0; i<diference;i++){
num2[i] = '0';
}
}else{
length = length2;
int diference = length2 - length1;
for(int i=length1; i>=0;i--){
num1[i+diference] = num1[i];
}
//You must collect the garbage
for(int i=0; i<diference;i++){
num1[i] = '0';
}
}
char res[(length+2)];
res[(length+1)] = '\0';
cout <<"===="<<endl;
cout<< "num1 : " << num1<< endl;
cout<< "num2 : " << num2<< endl;
for(int i=length;i>=0;i--){
/*0 - 1*/
if((num1[i] == '0' && num2[i] == '1')){
int j = i-1;
while(num1[j] != '1'){
j = j - 1;
}
num1[j] = '0';
res[i+1] = '1';
}
/*0 - 0*/
if(num1[i] == '0' && num2[i] == '0'){
res[i+1] = '0';
}
/*1 - 0*/
if((num1[i] == '1' && num2[i] == '0')){
res[i+1] = '1';
}
/*1 - 1*/
if(num1[i] == '1' && num2[i] == '1'){
res[i+1] = '0';
}
res[0] = '0';
}
cout<< "res : " << res<< endl;
return 0;
}
Your program is too long to do a quick analysis. I believe the best way for you to solve the problem is to use a Debugger. Now if the intention is to have an example of how to do binary arithmetic using C++, use the Std::bitset makes it so much easier.
– user5299