Java Program to subtract two binary numbers using ParseInt
Program
import java.util.Scanner;
public class SubtractTwoBinaryNumbersUsingParseInt {
public void subtractBinaryNumbers(String binaryNum1, String binaryNum2)
{
int num1 = Integer.parseInt(binaryNum1, 2);
int num2 = Integer.parseInt(binaryNum2, 2);
int difference = num1 - num2;
System.out.println(Integer.toBinaryString(difference));
}
public static void main(String[] args)
{
SubtractTwoBinaryNumbersUsingParseInt subtractTwoBinaryNumbersUsingParseInt= new SubtractTwoBinaryNumbersUsingParseInt();
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("Difference of two numbers is: ");
subtractTwoBinaryNumbersUsingParseInt.subtractBinaryNumbers(binaryNum1, binaryNum2);
}
}
This Java program subtracts two binary numbers by converting them into decimal format, performing the subtraction, and then converting the result back to binary.
Use Case:
This program is ideal when you need to subtract binary numbers in a straightforward manner, focusing on converting to decimal, performing arithmetic, and converting back to binary without handling low-level bit manipulation.
-
Input:
- The user is prompted to enter two binary numbers as strings using the
Scanner
class.
- The user is prompted to enter two binary numbers as strings using the
-
Conversion:
Integer.parseInt(binaryNum, 2)
:- Converts the input binary strings into decimal integers.
- The
2
argument specifies that the input is in binary format.
-
Subtraction:
- The two converted decimal numbers are subtracted.
-
Result Conversion:
Integer.toBinaryString(difference)
:- Converts the resulting decimal difference back into its binary representation.
-
Output:
- The program prints the binary form of the difference.
-
Example Execution:
- Example:
Enter the first binary number: 1011 Enter the second binary number: 0111 Difference of two numbers is: 100
- Steps:
- Convert
1011
(binary) to11
(decimal). - Convert
0111
(binary) to7
(decimal). - Subtract
11 - 7 = 4
(decimal). - Convert
4
(decimal) to100
(binary).
- Convert
- Example:
Key Features:
- Simplicity:
- Uses
Integer.parseInt
andInteger.toBinaryString
for efficient conversion between binary and decimal.
- Uses
- Direct Approach:
- The program directly handles the subtraction after converting both binary inputs to integers, avoiding manual binary subtraction.
- Accuracy:
- This approach ensures accurate results without the complexity of performing binary subtraction manually.
Output
$ javac SubtractTwoBinaryNumbersUsingParseInt.java
$ java SubtractTwoBinaryNumbersUsingParseInt
Enter the first binary number: 110111
Enter the second binary number: 101010
Difference of two numbers is: 1101