Function add two binary numbers in c++ -


in c++, how can write program read 2 binary numbers print result of addition, using function read binary numbers each number has 4-bit, , using function add (binary 1, binary 2) ?!

i find program don't want arrays, need functions.

#include <iostream> #include <string> using namespace std;  int main() { int a[4]; int b[4]; int carry=0; int result[5];   a[0]=1; a[1]=0; a[2]=0; a[3]=1;  b[0]=1; b[1]=1; b[2]=1; b[3]=1;  for(int i=0; i<4; i++) {      if(a[i]+b[i]+carry==3)     {     result[i]=1;     carry=1;     }     if(a[i]+b[i]+carry==2)     {     result[i]=0;     carry=1;     }     if(a[i]+b[i]+carry==1)     {     result[i]=1;     carry=0;     }     if(a[i]+b[i]+carry==0)     {     result[i]=0;     carry=0;     }   } result[4]=carry; for(int j=4; j>=0; j--) {     cout<<result[j];  } cout<<endl;      return 0; } 

there's no such one function unfortunately std::iostream , scanf-family supports oct, hex, dec not binary numeric representations.

basically, use strtol , itoa. latter not available on gcc (because it's not ansi-compliant), added snippet of implementation itoa.

#include <cstdio> #include <cstring> #include <cstdlib> using namespace std;  /*credit goes to: http://www.jb.man.ac.uk/~slowe/cpp/itoa.html*/ // should not need function if compiled smoothly without //  ( if you're on microsoft visual studio, don't need function char* itoa(int val, int base){       static char buf[33] = {0};       int = 30;      for(; val && ; --i, val /= base)           buf[i] = "0123456789abcdef"[val % base];         return &buf[i+1];    }  int main(){     int a,b;     char p[100];     printf("enter first number:\n");     scanf("%s",p);     = strtol(p,null,2);     printf("enter second number:\n");     scanf("%s",p);         b = strtol(p,null,2);     printf( itoa( a+b , 2 ) );     printf("\n"); } 

Comments

Popular posts from this blog

c# - Operator '==' incompatible with operand types 'Guid' and 'Guid' using DynamicExpression.ParseLambda<T, bool> -