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
89 views
in JAVA by (113k points)
Explain Java Convert Decimal to Binary

Please log in or register to answer this question.

1 Answer

0 votes
by (113k points)

Certainly! Converting a decimal number to binary involves representing the number in base 2, where each digit can be either 0 or 1. In Java, you can achieve this conversion using bitwise operations and loops. Here's an example code snippet that demonstrates how to convert a decimal number to binary:

public class DecimalToBinaryConverter {
    public static void main(String[] args) {
        int decimalNumber = 42; // Example decimal number

        System.out.println("Decimal Number: " + decimalNumber);
        System.out.println("Binary Equivalent: " + decimalToBinary(decimalNumber));
    }

    public static String decimalToBinary(int decimal) {
        if (decimal == 0) {
            return "0"; // Special case for decimal number 0
        }

        StringBuilder binary = new StringBuilder();
        while (decimal > 0) {
            int remainder = decimal % 2; // Get the remainder (either 0 or 1)
            binary.insert(0, remainder); // Prepend the remainder to the binary representation
            decimal /= 2; // Divide the decimal number by 2 for the next iteration
        }

        return binary.toString();
    }
}
 

In this example, we have a decimal number 42. The decimalToBinary method takes an integer decimal number as input and returns a string representing its binary equivalent.

We use a StringBuilder called binary to build the binary representation of the number. The method starts by checking if the decimal number is zero, in which case it directly returns "0" as the binary representation.

Inside the while loop, we repeatedly divide the decimal number by 2 and append the remainder (either 0 or 1) to the beginning of the binary string using the insert method. This process continues until the decimal number becomes zero.

Finally, we return the binary.toString() value, which is the binary representation of the input decimal number.

When you run the code, it will output:

Decimal Number: 42
Binary Equivalent: 101010
 

The decimal number 42 is converted to its binary equivalent, which is 101010.

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

...