Search code examples
c++outputaddition

Binary addition using char array


#include <iostream>
#include <cstdlib>
#include <cstring>
#include <stdio.h>


int main(){

    char Pbuf8[9]={"01100000"};
    char Mbuf4[10]={"01110000"};

    int num=0;
    char Snum[9]="0";   
    int carry=0;


    for(int c=7;c>=0;c--){

        //Convert a string to a number and add
        num=(Pbuf8[c]-'0')+(Mbuf4[c]-'0')+carry;

        //binary addition
        if(num==1){
            Snum[c]=num;
            carry=0;
        }else if(num==2){
            num=0;
            carry=1;
            Snum[c]=num;
        }else if(num==3){
            num=1;
            carry=1;
            Snum[c]=num;
        }
        //Convert num to string and store in Snum
        sprintf(Snum, "%d", num);  
    }
    //output
    printf("%s",Snum);
     

    return 0;
}

Calculate and output the sum of Pbuf8 and Mbuf4.

I want to output '00001011' but '1' is output.

If there is no 'sprintf(number, "%d", number);' does not exist, 'rr' is output.

How do I get the value I want?


Solution

  • You have 3 minor bugs in your code.

    • Snum must be initialized with everything being 0. Otherwise it will just be filled with one 0 and the lower part of the addition will not be visible
    • You need to convert "num" back to a number, before adding it back to the char array. So, num+'0'
    • Delete the "sprintf", It will overwrite the previously created result.

    The corrected code will look like:

    #include <iostream>
    #include <cstdlib>
    #include <cstring>
    #include <stdio.h>
    
    
    int main(){
    
        char Pbuf8[9]={"01100000"};
        char Mbuf4[10]={"01110000"};
    
        int num=0;
        char Snum[9]="00000000";   
        int carry=0;
    
    
        for(int c=7;c>=0;c--){
    
            //Convert a string to a number and add
            num=(Pbuf8[c]-'0')+(Mbuf4[c]-'0')+carry;
    
            //binary addition
            if(num==1){
                Snum[c]=num+'0';
                carry=0;
            }else if(num==2){
                num=0;
                carry=1;
                Snum[c]=num+'0';
            }else if(num==3){
                num=1;
                carry=1;
                Snum[c]=num+'0';
            }
            //Convert num to string and store in Snum
            //sprintf(Snum, "%d", num);  
        }
        //output
        printf("%s",Snum);
         
    
        return 0;
    }