Write A Java Program To Convert Binary To Decimal And Vice Versa Using The Function
In this article, you will learn how to convert numbers between their binary and decimal representations using custom functions in Java. We'll explore the logic behind these conversions and implement them with practical code examples.
Problem Statement
In computing, numbers are often represented in different bases. Humans typically use base-10 (decimal), while computers fundamentally operate using base-2 (binary). The need to convert between these two systems arises frequently in fields like network programming, low-level data manipulation, and understanding computer architecture. Converting accurately and efficiently is crucial for interpreting data correctly and for building robust applications.
Example
Let's quickly see an example of what these conversions look like:
- Binary to Decimal: The binary number
1011converts to the decimal number11. - Decimal to Binary: The decimal number
13converts to the binary number1101.
Background & Knowledge Prerequisites
To follow this article, a basic understanding of Java programming concepts is helpful, including:
- Variables and data types (integers, strings).
- Conditional statements (if/else).
- Loops (while, for).
- Basic arithmetic operations (addition, multiplication, division, modulo).
- Understanding of functions/methods in Java.
- The concept of number bases (binary, decimal).
Use Cases or Case Studies
Understanding and implementing binary-decimal conversion is vital in several practical scenarios:
- Networking: IP addresses are often represented in dotted-decimal format (e.g.,
192.168.1.1), but network devices process them in binary. Conversion is essential for subnetting calculations and packet analysis. - Low-Level Programming: When working with hardware interfaces, bitwise operations, or memory addresses, direct manipulation of binary values is common.
- Data Storage and Compression: Some data formats store information as sequences of bits. Converting these binary sequences to a readable decimal format helps in debugging and data interpretation.
- Digital Logic Design: Engineers designing digital circuits frequently switch between binary, decimal, and hexadecimal representations to represent logic states and memory contents.
- Cryptography: Many cryptographic algorithms rely on bitwise operations and modular arithmetic, making a strong grasp of binary representations important.
Solution Approaches
We will implement two primary functions: one for converting binary to decimal and another for decimal to binary. Then, we will integrate them into a main program.
Approach 1: Binary to Decimal Conversion
This approach converts a binary string to its equivalent decimal integer by summing the powers of 2 where a '1' is present in the binary string.
- Summary: Iterates through the binary string from right to left, multiplying each digit by the corresponding power of 2 and summing the results.
// Binary to Decimal Converter
import java.util.Scanner;
public class Main {
/**
* Converts a binary string to its decimal equivalent.
* @param binaryString The binary number as a string.
* @return The decimal equivalent of the binary string.
*/
public static int binaryToDecimal(String binaryString) {
int decimal = 0;
int power = 0; // Represents 2^0, 2^1, 2^2, ...
// Iterate through the binary string from right to left
for (int i = binaryString.length() - 1; i >= 0; i--) {
char bit = binaryString.charAt(i);
// If the bit is '1', add 2^power to the decimal number
if (bit == '1') {
decimal += Math.pow(2, power);
}
power++; // Increment power for the next bit
}
return decimal;
}
public static void main(String[] args) {
// Example usage
String binary = "1011";
int decimalResult = binaryToDecimal(binary);
System.out.println("Binary: " + binary + " -> Decimal: " + decimalResult); // Output: 11
}
}
- Sample Output:
Binary: 1011 -> Decimal: 11
- Stepwise Explanation:
- The
binaryToDecimalfunction takes aStringrepresenting the binary number. - It initializes
decimalto0(this will store the final decimal value) andpowerto0(this tracks the current power of 2, starting from 2^0 for the rightmost bit). - A
forloop iterates from the last character (rightmost bit) of the binary string to the first character (leftmost bit). - In each iteration, it extracts the current
bit. - If the
bitis'1', it calculates2raised to thepowerand adds it to thedecimalsum.Math.pow(2, power)computes 2^power. - The
poweris then incremented for the next bit position. - Finally, the accumulated
decimalvalue is returned.
Approach 2: Decimal to Binary Conversion
This approach converts a decimal integer to its binary string representation using repeated division by 2.
- Summary: Continuously divides the decimal number by 2, recording the remainder (0 or 1) at each step. The binary string is formed by reading the remainders in reverse order.
// Decimal to Binary Converter
import java.util.Scanner;
public class Main {
/**
* Converts a decimal integer to its binary string equivalent.
* @param decimal The decimal number.
* @return The binary string representation of the decimal number.
*/
public static String decimalToBinary(int decimal) {
if (decimal == 0) {
return "0"; // Special case for 0
}
StringBuilder binaryBuilder = new StringBuilder(); // To efficiently build the binary string
int tempDecimal = decimal;
// Perform repeated division by 2
while (tempDecimal > 0) {
int remainder = tempDecimal % 2; // Get the remainder (0 or 1)
binaryBuilder.append(remainder); // Append remainder to the builder
tempDecimal /= 2; // Divide the number by 2
}
// The binary string is built in reverse, so reverse it before returning
return binaryBuilder.reverse().toString();
}
public static void main(String[] args) {
// Example usage
int decimal = 13;
String binaryResult = decimalToBinary(decimal);
System.out.println("Decimal: " + decimal + " -> Binary: " + binaryResult); // Output: 1101
}
}
- Sample Output:
Decimal: 13 -> Binary: 1101
- Stepwise Explanation:
- The
decimalToBinaryfunction takes anintrepresenting the decimal number. - It handles the special case where
decimalis0, returning"0". - A
StringBuilderis used to efficiently build the binary string.StringBuilderis generally preferred overStringconcatenation in loops for performance. - A
whileloop continues as long astempDecimalis greater than0. - Inside the loop,
tempDecimal % 2calculates the remainder, which will be either0or1. This remainder is the next bit in the binary representation. - The
remainderis appended to thebinaryBuilder. tempDecimalis then divided by2(tempDecimal /= 2).- After the loop finishes, the
binaryBuildercontains the binary digits in reverse order (e.g., for 13, it will be "1011"). binaryBuilder.reverse().toString()reverses the string and converts it to a standardStringbefore returning.
Approach 3: Integrating Both Conversions with User Input
This approach combines both conversion functions into a single program that takes user input to demonstrate both conversions interactively.
- Summary: Uses
Scannerto get input from the user and then calls thebinaryToDecimalanddecimalToBinaryfunctions based on user's choice.
// Binary-Decimal Converter with User Input
import java.util.Scanner;
// Main class containing the entry point of the program
public class Main {
/**
* Converts a binary string to its decimal equivalent.
* @param binaryString The binary number as a string.
* @return The decimal equivalent of the binary string.
*/
public static int binaryToDecimal(String binaryString) {
int decimal = 0;
int power = 0;
for (int i = binaryString.length() - 1; i >= 0; i--) {
char bit = binaryString.charAt(i);
if (bit == '1') {
decimal += Math.pow(2, power);
} else if (bit != '0') {
// Handle invalid binary input
throw new IllegalArgumentException("Invalid binary string: " + binaryString);
}
power++;
}
return decimal;
}
/**
* Converts a decimal integer to its binary string equivalent.
* @param decimal The decimal number.
* @return The binary string representation of the decimal number.
*/
public static String decimalToBinary(int decimal) {
if (decimal == 0) {
return "0";
}
if (decimal < 0) {
// For simplicity, handle only positive integers. For negative, Two's Complement is needed.
throw new IllegalArgumentException("Negative numbers not supported for simple binary conversion.");
}
StringBuilder binaryBuilder = new StringBuilder();
int tempDecimal = decimal;
while (tempDecimal > 0) {
int remainder = tempDecimal % 2;
binaryBuilder.append(remainder);
tempDecimal /= 2;
}
return binaryBuilder.reverse().toString();
}
public static void main(String[] args) {
// Step 1: Create a Scanner object to read user input
Scanner scanner = new Scanner(System.in);
// Step 2: Prompt the user for the type of conversion
System.out.println("Choose conversion type:");
System.out.println("1. Binary to Decimal");
System.out.println("2. Decimal to Binary");
System.out.print("Enter your choice (1 or 2): ");
int choice = scanner.nextInt();
// Step 3: Perform conversion based on user's choice
try {
if (choice == 1) {
System.out.print("Enter a binary number: ");
String binaryInput = scanner.next();
int decimalResult = binaryToDecimal(binaryInput);
System.out.println("Decimal equivalent: " + decimalResult);
} else if (choice == 2) {
System.out.print("Enter a decimal number: ");
int decimalInput = scanner.nextInt();
String binaryResult = decimalToBinary(decimalInput);
System.out.println("Binary equivalent: " + binaryResult);
} else {
System.out.println("Invalid choice. Please enter 1 or 2.");
}
} catch (IllegalArgumentException e) {
System.err.println("Error: " + e.getMessage());
} finally {
// Step 4: Close the scanner to prevent resource leaks
scanner.close();
}
}
}
- Sample Output (User Input - Choice 1):
Choose conversion type:
1. Binary to Decimal
2. Decimal to Binary
Enter your choice (1 or 2): 1
Enter a binary number: 1101
Decimal equivalent: 13
- Sample Output (User Input - Choice 2):
Choose conversion type:
1. Binary to Decimal
2. Decimal to Binary
Enter your choice (1 or 2): 2
Enter a decimal number: 25
Binary equivalent: 11001
- Stepwise Explanation:
- The
mainmethod usesScannerto get input from the user. - It prompts the user to choose between "Binary to Decimal" (1) and "Decimal to Binary" (2).
- Based on the
choice, it then prompts for the appropriate number type. - It calls either
binaryToDecimal()ordecimalToBinary()with the user's input. - Error handling is included to catch
IllegalArgumentExceptionfor invalid binary strings or negative decimal inputs (for which a more complex conversion like Two's Complement would be needed). - The
Scanneris closed in afinallyblock to ensure resource cleanup.
Conclusion
We have explored the fundamental methods for converting between binary and decimal number systems in Java. By implementing dedicated functions for each conversion, we ensure code modularity, reusability, and clarity. The binary-to-decimal conversion leverages positional notation with powers of two, while the decimal-to-binary conversion uses successive division by two and collecting remainders. These functions, when combined, provide a robust solution for number base transformations essential in various computing contexts.
Summary
- Binary to Decimal: Sums powers of 2 for '1' bits, iterating from right to left.
- Decimal to Binary: Uses repeated division by 2, collecting remainders and reversing them.
- Java Functions:
binaryToDecimaltakes aStringand returns anint;decimalToBinarytakes anintand returns aString. -
StringBuilder: Efficiently constructs the binary string by appending characters. -
Scanner: Facilitates interactive user input for conversion choices. - Error Handling: Important for robust applications, catching invalid inputs.