Pages

Saturday, July 4, 2020

Java Program to Add Two Binary Numbers

1. Introduction


In this tutorial, You will learn a java program on how to add two binary numbers in binary format. Binary numbers are represented in only '0' and '1's. This is not having any other numbers. If a number has digits apart from 0 and 1 it is not a binary number. I have seen many examples on the internet all are showing only programs but giving the explanation. Here it is different than the Bitwise AND operator. It looks like & operator but not. You will get clarified in this article. Do not skip any content and also do not see the code directly.

Java Program to Add Two Binary Numbers


We have already discussed in previous articles on how to add two numbers in java. This is a very basic program but a common interview question. To make this complicated interviewer will ask to do not use + operator to make the sum of two numbers.



Usually this can be done in two ways. in frist way, we do not use any java API methods and just use the engineering concept from Switching theory & Logic Design (STLD) subject and in the second approach is done using Integer API.

binary number sequence addition works as follows.

Adding two binary '1's like 1 + 1 will produce digit 2 in decimal but we should convert it to binary which is 10. Here 0 is the actual sum and 1 is a carry.
0 + 0 will produce 0
0 + 1 -> 1
1 + 0 -> 1

Here all outputs are should be in binary digits and no decimal number digits are allowed.

2. Algorithm walkthrough with example: Adding Two Binay Numbers In Java


Taking two binary numbers for demonstration.

binaryNumber1 = 10101
binaryNumber2 = 10001
carry = 0

Iteration 1:


10101
10001

carry + first digit from binaryNumber1 + first digit from binaryNumber2
0 + 1 + 1 = 10 (this is a binary number) here it is combination of  carry + sum. so here carry and sum as follows.
carry = 1
first digit sum = 0

Iteration 2:


10101
10001

carry (from previous step) + second digit from binaryNumber1 + second digit from binaryNumber2
1 + 0 + 0 = 01
carry = 0
second digit sum = 1

Iteration 3:


10101
10001

carry (from previous step) + third digit from binaryNumber1 + third digit from binaryNumber2
0 + 1 + 0 = 01
carry = 0
third digit sum = 1


Iteration 4:


10101
10001

carry (from previous step) + fourth digit from binaryNumber1 + fourth digit from binaryNumber2
0 + 0 + 0 = 0
carry = 0
fourth digit sum = 0

Iteration 5:


10101
10001

carry (from previous step) + fifth digit from binaryNumber1 + fifth digit from binaryNumber2
0 + 1 + 1 = 10
carry = 1
fifth digit sum = 0


Output:


Formula: 

carry + all digts sum (fifth digit sum  fourth digit sum  third digit sum  second digit sum  first digit sum )

100110

[post_ads]

3. Example Program to add two binary numbers

The above example values are passed to this program and produce the same output.

package com.java.w3schools.blog.java.program.to;

/**
 * 
 * Program to add two binary numbers in java
 * 
 * @author venkateshn
 *
 */
public class AddBinaryNumbers {

 public static void main(String[] args) {

  // two binary numbers
  long binaryNumber1 = 10101, binaryNumber2 = 10001;

  // i represents the index of the finalSumOutput array.
  int i = 0;
  
  // carry which is to hold the value of carry.
  int carry = 0;

  // Created int array to hold the output binary number
  int[] finalSumOutput = new int[10];

  while (binaryNumber1 != 0 || binaryNumber2 != 0) {

   finalSumOutput[i++] = (int) (carry + (binaryNumber1 % 10 + binaryNumber2 % 10) % 2);

   carry = (int) ((binaryNumber1 % 10 + binaryNumber2 % 10 + carry) / 2);

   binaryNumber1 = binaryNumber1 / 10;
   binaryNumber2 = binaryNumber2 / 10;
  }
  if (carry != 0) {
   finalSumOutput[i++] = carry;
  }
  --i;
  System.out.print("Output: ");
  // printing from the last index to 0.
  while (i >= 0) {
   System.out.print(finalSumOutput[i--]);
  }
  System.out.print("\n");
 }

}

Output:

Output: 100110

Java Program to Add Two Binary Numbers- way 1

[post_ads]

4. Second Approach To Add Binary Numbers


Java API Integer class has parseInt() method which takes string and radix. If we pass radix value 2 then it considers the string values binary number. Next, we perform sum and pass the output int value to toBinaryString() method which converts integer back to binary number. We need the disired output in binary format.

Let us take a look at the below program.

package com.java.w3schools.blog.java.program.to;

/**
 * 
 * Program to add two binary numbers in java using Integer API.
 * 
 * @author venkateshn
 *
 */
public class AddBinaryNumbersWay2 {

 public static void main(String[] args) {

  // two binary numbers in string format
  String binaryNumber1 = "10101", binaryNumber2 = "10001";

  // converting strings into binary format numbers 
  Integer integer1 = Integer.parseInt(binaryNumber1, 2);
  Integer integer2 = Integer.parseInt(binaryNumber2, 2);

  // adding two integers
  Integer output = integer1 + integer2;
  
  // converting final output back to Binary Integer
  System.out.println(Integer.toBinaryString(output));

 }

}

Output:

In both approaches, the same input is taken. Observer that outputs are also same. Both are producing the results as expected.


100110

Java Program to Add Two Binary Numbers - way 2 using Integer API


5. Conclusion


In this article, You have learned how to write a java program to add two binary numbers. This can be done in two ways. The first way is without using any java API methods and use completely Switching Theory & Logic Design ( STLD ) logic. The second approach is using Integer wrapper class radix option.

Hope you enjoyed the article. Please share it with friends.

Post your questions in the comments section.

Ref

No comments:

Post a Comment

Please do not add any spam links in the comments section.