I am trying to add two binary numbers in a c function, and I can't get the result I'm looking for.
#include <string.h>
#include <stdio.h>
char * sadd(char bn1[], char bn2[], char s[]){ //Function to add the binary numbers
int i;
int co = 0;
int num = 0;
for(i = 15; i>0; i ){
num = (int)bn1[i] (int)bn2[i] co;
co = 0;
if(num == 2){
co = 1;
s[i] = '0';
}
else{
s[i] = (char)num;
}
}
return s;
}
CodePudding user response:
This for loop
for(i = 15; i>0; i ){
is incorrect. Instead of decreasing the variable i it is increased. It seems you mean
for(i = 15; i>=0; i--){
This statement
num = (int)bn1[i] (int)bn2[i] co;
should be rewritten like
num = bn1[i] - '0' bn2[i] - '0' co;
And this statement
s[i] = (char)num;
should be rewritten like
s[i] = num '0';
And you are not processing the case when num is equal tp 3 when co is equal to 1 and bn[i] and bn2[i] are both equal to '1'.
Instead of this if statement
co = 0;
if(num == 2){
co = 1;
s[i] = '0';
}
else{
s[i] = (char)num;
}
you could just write
s[i] = num % 2 '0';
cp = num / 2;
CodePudding user response:
@VladFromMoscow has provided a patient and valid answer. But - you could have figured this out on your own, if you were to step through a run of your program, using a debugger.
Here are two Stackoverflow questions about debugging on Linux and on Windows:
If you were to debug the program, stepping through individual commands, you would notice that:
- The loop runs for more than 15 iterations, with
jincreasing. - The value of num is rarely between
0and3.
and then you could have thought about why that happens, and reached the same conclusion as in Vlad's answer.
Also, and for future reference - most StackOverflow users expect question askers to perform their "due diligence", making reasonable efforts to figure out their problems before asking us for a solution. Now that you know about debuggers - please use one before asking "Why does my program not do what I expected".
