Use app×
Join Bloom Tuition
One on One Online Tuition
JEE MAIN 2025 Foundation Course
NEET 2025 Foundation Course
CLASS 12 FOUNDATION COURSE
CLASS 10 FOUNDATION COURSE
CLASS 9 FOUNDATION COURSE
CLASS 8 FOUNDATION COURSE
0 votes
91 views
in JAVA by (113k points)
Explain Java Convert Binary to Decimal

Please log in or register to answer this question.

1 Answer

0 votes
by (113k points)

Certainly! Here's an example Java code that converts a binary number to its decimal equivalent:

public class BinaryToDecimalConverter {
    public static void main(String[] args) {
        String binaryNumber = "101010"; // Example binary number
        
        int decimalNumber = binaryToDecimal(binaryNumber);
        
        System.out.println("Binary Number: " + binaryNumber);
        System.out.println("Decimal Number: " + decimalNumber);
    }
    
    public static int binaryToDecimal(String binaryNumber) {
        int decimalNumber = 0;
        int power = 0;
        
        // Start from the rightmost bit and move towards the left
        for (int i = binaryNumber.length() - 1; i >= 0; i--) {
            int bit = binaryNumber.charAt(i) - '0'; // Convert char to integer
            
            // Multiply the bit value with 2 raised to the power
            decimalNumber += bit * Math.pow(2, power);
            power++;
        }
        
        return decimalNumber;
    }
}
 

In this example, we have a method called binaryToDecimal that takes a binary number as a string parameter and returns its decimal equivalent as an integer. The main method demonstrates how to use this method by converting the binary number "101010" to decimal.

The binaryToDecimal method works by iterating through each bit of the binary number from right to left. It converts the character at each position to an integer by subtracting the ASCII value of '0'. It then multiplies the bit value with 2 raised to the appropriate power and adds it to the decimalNumber variable. The power starts from 0 and increments by 1 for each subsequent bit.

After the loop, the decimalNumber is returned and printed in the main method.

When you run the code, it will output:

Binary Number: 101010
Decimal Number: 42
 

So, the binary number "101010" is equivalent to the decimal number 42.

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

Welcome to Sarthaks eConnect: A unique platform where students can interact with teachers/experts/students to get solutions to their queries. Students (upto class 10+2) preparing for All Government Exams, CBSE Board Exam, ICSE Board Exam, State Board Exam, JEE (Mains+Advance) and NEET can ask questions from any subject and get quick answers by subject teachers/ experts/mentors/students.

Categories

...