1. Introduction
In this tutorial, we will explore how to create a Java program to convert a binary number to its decimal equivalent. This type of conversion is common in computing and digital electronics, as it allows us to move between different numeral systems.
2. Program Steps
1. Define a class named BinaryToDecimal.
2. Inside the class, define the main method.
3. Inside the main method, declare a long variable to represent the binary number.
4. Initialize a variable to hold the decimal value, and another variable to keep track of the position of the binary digits.
5. Use a while loop to iterate through the binary number, converting each digit to its decimal equivalent and adding it to the decimal value.
6. Print out the binary number and its decimal equivalent.
3. Code Program
public class BinaryToDecimal { // Step 1: Define a class named BinaryToDecimal
public static void main(String[] args) { // Step 2: Define the main method
// Step 3: Declare a long variable to represent the binary number
long binary = 110101;
// Step 4: Initialize variables for decimal value and binary digit position
int decimal = 0;
int position = 0;
// Step 5: Use a while loop to iterate through the binary number and convert to decimal
while (binary != 0) {
long lastDigit = binary % 10; // get the last digit of binary number
decimal += lastDigit * Math.pow(2, position); // convert to decimal and add to total
binary = binary / 10; // remove the last digit from binary number
position++; // move to the next binary digit position
}
// Step 6: Print the binary number and its decimal equivalent
System.out.println("Binary Number: 110101");
System.out.println("Decimal Equivalent: " + decimal);
}
}
Output:
Binary Number: 110101 Decimal Equivalent: 53
4. Step By Step Explanation
– Step 1: A class named BinaryToDecimal is defined.
– Step 2: The main method is defined within the BinaryToDecimal class.
– Step 3: A long variable binary is declared to represent the binary number.
– Step 4: Variables decimal and position are initialized to hold the decimal value and keep track of the binary digit position, respectively.
– Step 5: A while loop is used to iterate through each digit of the binary number, converting it to its decimal equivalent and adding it to the total decimal value.
– Step 6: The original binary number and its decimal equivalent are printed to the console.