Addition of binary numbers in C++

In this article, we are going to learn how to add binary numbers in C++. A binary number is written in the base-2 numeral system, which for representation uses only “0” and “1”. Also, we are going to use the <math.h> library that declares a set of functions to compute mathematical operations and functions.

All the functions in this library take the data type double as an argument and return double as the result.

Addition of binary numbers in C++

Let us first discuss some basic bit-wise binary addition:

0+0 = 0

0+1 = 1

1+1 = 0 and carry-over 1

1+1+1 = 1 and carry-over 1

Now, let us look at an example,

Input1: 1010

Input2: 0011

Sum:     1101

In the above example, starting from the right, 0+1 = 1. Next 1+1 = 0 and 1 is carried over to the next place, thus making it 1+0+0 = 1. At the leftmost, we have 1+0 = 1. Thus, we get the output of 1101 which is 13 in decimal number system.

Code Implementation:

#include <iostream>
#include <math.h>
using namespace std;
 
int main()
{
  long bn1,bn2;
  int i=0, r=0;
  int sum[20]; 
    cout << "\n\n Addition of two binary numbers:\n";
  cout << "\n";
  cout << " Input the 1st binary number: ";
  cin>> bn1;
  cout << " Input the 2nd binary number: ";
  cin>> bn2;
  while (bn1 != 0 || bn2 != 0) 
  {
   sum[i++] = (int)((bn1 % 10 + bn2 % 10 + r) % 2);
   r = (int)((bn1 % 10 + bn2 % 10 + r) / 2);
   bn1 = bn1 / 10;
   bn2 = bn2 / 10;
  }
  if (r != 0) {
   sum[i++] = r;
  }
  --i;
  cout<<" The sum of two binary numbers is: ";
  while (i >= 0) {
   cout<<(sum[i--]);
  }
   cout<<("\n");  
 }

In the above code, in line numbers 18 and 19 we have done explicit type casting which converts any pointer into any other pointer type, independent of the types they point to.

I hope, you have understood how our program works to add binary numbers in C++ language.

Mention below your comments, if you find any mistake in the article or to share more information related to the topic of this article.

You may also learn,

Also read: Arithmetic expression evaluation program in C++

Leave a Reply

Your email address will not be published.