Multiplication of two binary numbers in Java

Hi, today we will learn the Multiplication of two binary numbers in Java.

first of all, those numbers that are expressed through 0’s and 1’s are known as binary numbers.

Please Remember there could be multiple ways to solve this given problem as per your understanding. for example:

  1. We can apply a direct algorithm that is designed to multiply two binary numbers.
  2. We can first convert the both binary n0’s to base 10 i.e. decimal and then simply just multiply them and then again convert the result back to base 2 i.e in binary format.

In this tutorial, we will use the first approach:

Multiplication of two binary numbers: Java Code

Below is the Java code to multiply two binary numbers.

import java.util.Scanner;
public class Main {

  static long calc(long b1, long b2) {
    int i = 0;
    long rmndr = 0;
    long result = 0;
    long[] sum = new long[20];
    while (b1 != 0 || b2 != 0) {                  //actual multiplying process-heart of this program
      sum[i++] = (b1 % 10 + b2 % 10 + rmndr) % 2;     
      rmndr = (b1 % 10 + b2 % 10 + rmndr) / 2;
      b1 = b1 / 10;
      b2 = b2 / 10;
    }
    if (rmndr != 0) {
      sum[i++] = rmndr;
    }--i;
    while (i >= 0) {                              //forming the result
      result = result * 10 + sum[i--];
    }
    return result;
  }
  public static void main(String[] args) {
    long b1, b2, m = 0;
    long d, f = 1;
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter A: ");
    b1 = sc.nextLong();
    System.out.println("\nEnter B: ");
    b2 = sc.nextLong();
    while (b2 != 0) {
      d = (b2 % 10);
      if (d == 1) {
        b1 = b1 * f;
        m = calc(b1, m);
      } else {
        b1 = b1 * f;
      }
      b2 = b2 / 10;
      f = 10;
    }
    System.out.println("\nA X B is: " + m + "\n");
  }
}

Output:

Enter A: 11100      // input A
Enter B: 10101      // input B
A X B is: 1001001100

You may read these:

Explanation:




you can easily understand with the help of the following flowcharts:

working of the main() method:

Multiplication of two binary numbers in Java

working of calc() method:

multiply two binary numbers in Java

So now you understood how to multiply two binary numbers. Feel free to comment if you have any doubt or a better approach. Also, you can try to implement the second approach.

you may also like:

Decimal to Binary conversion in JAVA


Leave a Reply

Your email address will not be published. Required fields are marked *