Binary Multiplication in Java

Binary multiplication in java. A binary number is a number expressed in the base-2 numeral system, also known as the binary numeral system, in digital electronics and mathematics.

Binary Numbers in Java

A binary number is made up of two digits: 0s and 1s. Binary numbers have a base of 2 and are represented as such. (101)2 ( 101 ) 2 is an example. A bit is a name given to each digit in a binary integer.

Long Keyword in Java

A minimum value of -263 and a maximum value of 263-1 can be found in the long. Long can now be represented as an unsigned 64-bit long with a minimum value of 0 and a maximum value of 264-1 in Java 8. 0L is the default value. It has an 8-byte default size. It’s utilized when you need an integer value with a larger range.

import java.util.Scanner;
public class Main {
public static void main(String[] args)
{
long bin1, bin2, multiply = 0;
int digit, factor = 1;
Scanner in = new Scanner(System.in);
System.out.print("first bin number");
bin1 = in.nextLong();
System.out.print("second bin number");
bin2 = in.nextLong();
while (bin2 != 0)
{
digit = (int)(bin2 % 10);
if (digit == 1)
{
bin1 = bin1 * factor;
multiply = binproduct((int) bin1, (int) multiply);
}
else
{
bin1 = bin1 * factor;
}
bin2 = bin2 / 10;
factor = 10;
}
System.out.print("Two Bin Number " + multiply+"\n");
}
static int binproduct(int bin1, int bin2)
{
int i = 0, remainder = 0;
int[] sum = new int;
int bin_prod_result = 0;

while (bin1 != 0 || bin2 != 0)
{
sum[i++] = (bin1 % 10 + bin2 % 10 + remainder) % 2;
remainder = (bin1 % 10 + bin2 % 10 + remainder) / 2;
bin1 = bin1 / 10;
bin2 = bin2 / 10;
}
if (remainder != 0)
{
sum[i++] = remainder;
}
--i;
while (i >= 0)
{
bin_prod_result = bin_prod_result * 10 + sum[i--];
}
return bin_prod_result;
}
}

Output:

First binary number: 110

Second binary number: 101

Product of two binary numbers: 11110