Ads

Tutorials

# Conversion of Decimal to Binary in Java

In this section, you will learn to convert decimal number into binary.

In this section, you will learn to convert decimal number into binary.

## Conversion of Decimal to Binary  in Java

In this section we will discuss about conversion of Decimal to Binary in Java. You know that number having base 10 is a decimal number, for example 10 is a decimal number which can be converted to binary and written as 1010.

Example : Convert 12 into binary number. Using the table below  will show how division is done.

 2 12 Remainder 2 6 0 2 3 0 2 1 1 1

Now, note down the remainder from bottom to top i.e. 1100(Binary equivalent of 12).

Example : Using this example we pass a decimal number in the command line argument  and divide that number by 2 and the remainder which we get is noted down. The remainder we get is the binary number. Now here is the code for conversion.

```class Conversion {
public static void main(String args[]) {
int n;
int i = 0;
int b[] = new int;
n = Integer.parseInt(args);
while (n != 0) {
i++;
b[i] = n % 2;
n = n / 2;
}
for (int j = i; j > 0; j--) {
System.out.print(b[j]);
}
}
}```

Output from the program: Download Source Code

The java.lang. package provide one function to convert into decimal i.e. toBinaryString()  method .

Syntax:

toBinaryString()

This method returns a string representation of the integer argument as an  integer in base 2.

Example : Code to convert Decimal to Binary using toBinaryString() method

```import java.lang.*;

public class ConversionDemo {

public static void main(String[] args) {

int i = 12;

System.out.println("Binary is " + Integer.toBinaryString(i));

}
}```

Output from the program. .

Download Source Code

Ads

Ads