Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,892 questions

51,823 answers

573 users

How to add two numbers using bitwise (binary) operators in C

3 Answers

0 votes
#include <stdio.h>
 
int binaryAdd(int a, int b) 
{
      int carry; 
      while (b != 0) {
             carry = (a & b) << 1;
             a = a ^ b;
             b = carry;
      }
      return a; 
}
 
int main() 
{
    int a = 3, b = 7;
  
    printf("%d\n", binaryAdd(a, b));
 
    return 0;
}
  
/*
 
run:
 
10
 
*/

 



answered Jul 21, 2018 by avibootz
edited Jul 21, 2018 by avibootz
0 votes
#include <stdio.h>
 
int binaryAdd(int a, int b) 
{
    static int sum = 0, carry = 0;
    
    if (b == 0) {
        return a;
    }
    else {
            sum = a ^ b;
            carry = (a & b) << 1;
            return binaryAdd(sum, carry);         
    }
}
 
int main() 
{
    int a = 5, b = 7;
  
    printf("%d\n", binaryAdd(a, b));
 
    return 0;
}
  
/*
 
run:
 
12
 
*/

 



answered Jul 21, 2018 by avibootz
0 votes
#include <stdio.h>
  
int binaryAdd(int a, int b) 
{
    if (b == 0)
        return a;
    else
        return binaryAdd(a ^ b, (a & b) << 1);
}
 
int main()
{
    int a = 4 ,b = 7;
    
    printf("%d\n", binaryAdd(a, b));
    
    return 0;
}
   
/*
  
run:
  
11
  
*/

 



answered Jul 21, 2018 by avibootz

Related questions

1 answer 161 views
2 answers 242 views
1 answer 178 views
2 answers 217 views
...