Java: Multiply two binary numbers
Binary Multiplication
Write a Java program to multiply two binary numbers.
In digital electronics and mathematics, a binary number is a number expressed in the base-2 numeral system or binary numeral system. This system uses only two symbols: typically 1 (one) and 0 (zero).
Test Data:
Input first binary number: 110
Input second binary number: 101
Sample Solution:
Java Code:
Explanation:
In the exercise above -
- Initialize variables to store the two binary numbers ('binary1' and 'binary2'), the result 'multiply', and other necessary variables.
- Take two binary numbers from the user using the Scanner class.
- Next, it enters a loop to perform binary multiplication by considering the digits of the second binary number one by one from right to left.
- For each digit in 'binary2', if it's 1, it multiplies 'binary1' by a factor. It computes the product using the "binaryproduct()" function.
- The helper function "binaryproduct()" calculates the binary product of two numbers and returns the result.
- If the digit in binary2 is 0, it still multiplies 'binary1' by the factor but doesn't perform the product calculation.
- It updates 'binary2' by moving to the next digit (right to left) and adjusting the factor.
- After the loop, it prints the product of the two binary numbers, which is stored in the multiply variable.
Sample Output:
Input the first binary number: 110 Input the second binary number: 101 Product of two binary numbers: 11110
Flowchart:
Flowchart : binaryproduct()
For more Practice: Solve these Related Problems:
- Multiply three binary numbers instead of two.
- Perform binary multiplication without converting to decimal.
- Write a program that multiplies binary numbers of different bit lengths.
- Modify the program to multiply a binary number by a decimal number directly.
Go to:
PREV : Binary Addition.
NEXT : Decimal to Binary Converter.
Java Code Editor:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.