Binary to Decimal Converter
This program converts binary numbers to their decimal equivalents. The conversion is done using a Java program.
Java Program
/**
* This Java program converts a binary number (represented as a string) to its decimal equivalent.
* The main method reads a binary number from the command line arguments and prints its decimal equivalent.
*/
public class BinaryToDecimalConverter {
/**
* Converts a binary number (as a string) to its decimal equivalent.
*
* @param binaryString The binary number as a string.
* @return The decimal equivalent of the binary number.
* @throws IllegalArgumentException If the input string is not a valid binary number.
*/
public static int convertBinaryToDecimal(String binaryString) {
// Validate the binary string
if (!binaryString.matches("[01]+")) {
throw new IllegalArgumentException("Invalid binary number: " + binaryString);
}
int decimal = 0;
int length = binaryString.length();
// Convert binary to decimal
for (int i = 0; i < length; i++) {
char binaryChar = binaryString.charAt(length - 1 - i);
int binaryDigit = Character.getNumericValue(binaryChar);
decimal += binaryDigit * Math.pow(2, i);
}
return decimal;
}
public static void main(String[] args) {
if (args.length != 1) {
System.out.println("Usage: java BinaryToDecimalConverter <binary_number>");
return;
}
String binaryString = args[0];
try {
int decimal = convertBinaryToDecimal(binaryString);
System.out.println("The decimal equivalent of binary number " + binaryString + " is: " + decimal);
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
}
}
Explanation
The program consists of two main components:
convertBinaryToDecimal
method: This method takes a binary string as input and converts it to a decimal integer. It validates the input to ensure it contains only binary digits (0 and 1). It then iterates through each character of the binary string, calculates the corresponding decimal value, and accumulates the result.main
method: This method serves as the entry point of the program. It checks if a single command-line argument is provided (the binary number). If the input is valid, it calls theconvertBinaryToDecimal
method and prints the result. If the input is invalid, it displays an error message.
How to Run the Program
To compile and run the program, follow these steps:
- Save the code in a file named
BinaryToDecimalConverter.java
. - Open a terminal or command prompt and navigate to the directory containing the file.
- Compile the program using the command:
javac BinaryToDecimalConverter.java
- Run the program using the command:
java BinaryToDecimalConverter <binary_number>
, replacing<binary_number>
with the binary number you want to convert.
Example:
java BinaryToDecimalConverter 1010
This command will output:
The decimal equivalent of binary number 1010 is: 10