Java Program to multiply two binary numbers using ParseInt
Program
import java.util.Scanner;
public class MultiplyTwoBinaryNumbersUsingParseInt {
public void multiplyBinaryNumbers(String binaryNum1, String binaryNum2)
{
int num1 = Integer.parseInt(binaryNum1, 2);
int num2 = Integer.parseInt(binaryNum2, 2);
int product = num1 * num2;
System.out.println(Integer.toBinaryString(product));
}
public static void main(String[] args)
{
MultiplyTwoBinaryNumbersUsingParseInt multiplyTwoBinaryNumbersUsingParseInt= new MultiplyTwoBinaryNumbersUsingParseInt();
Scanner reader = new Scanner(System.in);
System.out.print("Enter the first binary number: ");
String binaryNum1 = reader.nextLine();
System.out.print("Enter the second binary number: ");
String binaryNum2 = reader.nextLine();
System.out.print("Product of two numbers is: ");
multiplyTwoBinaryNumbersUsingParseInt.multiplyBinaryNumbers(binaryNum1, binaryNum2);
}
}
This Java program multiplies two binary numbers by converting them to decimal, performing multiplication, and then converting the result back to binary.
Use Case:
This program is well-suited for tasks requiring binary multiplication with minimal effort, as it handles the conversions and arithmetic internally using Java's built-in methods.
-
Input:
- The program uses the
Scanner
class to take two binary numbers as input from the user in the form of strings.
- The program uses the
-
Conversion to Decimal:
Integer.parseInt(binaryNum, 2)
:- Converts the binary input strings to their equivalent decimal integers.
- The
2
indicates that the input string is in binary format.
-
Multiplication:
- The two decimal numbers obtained from the conversion are multiplied.
-
Conversion Back to Binary:
Integer.toBinaryString(product)
:- Converts the product (a decimal number) back to its binary string representation.
-
Output:
- The program prints the binary representation of the product.
-
Example Execution:
- Example:
Enter the first binary number: 101 Enter the second binary number: 11 Product of two numbers is: 1111
- Steps:
- Convert
101
(binary) to5
(decimal). - Convert
11
(binary) to3
(decimal). - Multiply:
5 * 3 = 15
(decimal). - Convert
15
(decimal) to1111
(binary).
- Convert
- Example:
Key Features:
- Efficiency:
- Uses built-in methods (
Integer.parseInt
andInteger.toBinaryString
) to handle binary-decimal conversions efficiently.
- Uses built-in methods (
- Direct Approach:
- Directly multiplies the two numbers after converting them to decimal, avoiding manual binary multiplication.
- Simplicity:
- Reduces the complexity of binary multiplication by leveraging decimal arithmetic.
Output 1
$ javac MultiplyTwoBinaryNumbersUsingParseInt.java
$ java MultiplyTwoBinaryNumbersUsingParseInt
Enter the first binary number: 1101
Enter the second binary number: 111
Product of two numbers is: 1011011
Output 2
$ java MultiplyTwoBinaryNumbersUsingParseInt
Enter the first binary number: 1100
Enter the second binary number: 0
Product of two numbers is: 0