Conversion of Decimal to Binary in Java

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.


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[10];
		n = Integer.parseInt(args[0]);
		while (n != 0) {
			b[i] = n % 2;
			n = n / 2;
		for (int j = i; j > 0; j--) {

Output from the program:

Download Source Code

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



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

Share on Google+Share on Google+

Conversion of Decimal to Binary in Java

Posted on: July 25, 2013 If you enjoyed this post then why not add us on Google+? Add us to your Circles



Discuss: Conversion of Decimal to Binary in Java  

Post your Comment

Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image