Search code examples
cfor-loopcharfunction-definition

Binary addition in c with character arrays


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;
}

Solution

  • 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;