Perform Binary Addition : I/P to the function

Home Forums Programming Perform Binary Addition : I/P to the function

Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
    Posts
  • #1371
    RoboCop
    Participant

    Implement a function that performs binary addition; Input to the function is 2 constant strings. The function returns a string that holds result of addition.

    Ex: “1001” + “101” = “1110”

    char* binaryadd(const char *a, const char *b) { }

    #1372
    Satish
    Keymaster
    
    #include<stdio.h>
    #include<conio.h>
    #include<stdlib.h>
    
    long bintodeci(long n)
    {
      int base = 1, rem;
      long res = 0;
    
      while( n > 0 )
      {
        rem = n % 10;
        res = res + rem * base;
        base= base * 2;
        n   = n / 10;
      }
      return(res);
    }
    
    long decitobin(long n)
    {
      int base = 1, rem;
      long res = 0;
    
      while( n > 0 )
      {
        rem = n % 2;
        res = res + rem * base;
        base= base * 10;
        n   = n / 2;  
      }
      return(res);
    }
    
    
    char* binaryadd(const char *a, const char *b)
    {
      long no1, no2, res;
      char *ep;
    
      no1 = atol(a);
      no2 = atol(b);
    
      no1 = bintodeci(no1);
      no2 = bintodeci(no2);
    
      res = no1 + no2;
    
      res = decitobin(res);
    
      ltoa(res, ep, 10);
     
      // printf("%ld", res);
    
      return(ep);
    }
    
    
    void main()
    {
      char *result;
      clrscr();
    
      result = binaryadd("100", "111");
      
      printf("Result = %s", result);
    
      getch();
    }
    
Viewing 2 posts - 1 through 2 (of 2 total)
  • You must be logged in to reply to this topic.