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
    1. #include<stdio.h>  
    2. #include<conio.h>  
    3. #include<stdlib.h>  
    4.   
    5. long bintodeci(long n)  
    6. {  
    7.   int base = 1, rem;  
    8.   long res = 0;  
    9.   
    10.   while( n > 0 )  
    11.   {  
    12.     rem = n % 10;  
    13.     res = res + rem * base;  
    14.     base= base * 2;  
    15.     n   = n / 10;  
    16.   }  
    17.   return(res);  
    18. }  
    19.   
    20. long decitobin(long n)  
    21. {  
    22.   int base = 1, rem;  
    23.   long res = 0;  
    24.   
    25.   while( n > 0 )  
    26.   {  
    27.     rem = n % 2;  
    28.     res = res + rem * base;  
    29.     base= base * 10;  
    30.     n   = n / 2;    
    31.   }  
    32.   return(res);  
    33. }  
    34.   
    35.   
    36. char* binaryadd(const char *a, const char *b)  
    37. {  
    38.   long no1, no2, res;  
    39.   char *ep;  
    40.   
    41.   no1 = atol(a);  
    42.   no2 = atol(b);  
    43.   
    44.   no1 = bintodeci(no1);  
    45.   no2 = bintodeci(no2);  
    46.   
    47.   res = no1 + no2;  
    48.   
    49.   res = decitobin(res);  
    50.   
    51.   ltoa(res, ep, 10);  
    52.    
    53.   // printf("%ld", res);  
    54.   
    55.   return(ep);  
    56. }  
    57.   
    58.   
    59. void main()  
    60. {  
    61.   char *result;  
    62.   clrscr();  
    63.   
    64.   result = binaryadd("100""111");  
    65.     
    66.   printf("Result = %s", result);  
    67.   
    68.   getch();  
    69. }  
Viewing 2 posts - 1 through 2 (of 2 total)
  • You must be logged in to reply to this topic.