Home Java Java-conversion Conversion of Decimal to Binary in Java
Questions:Ask|Latest


 
 

Share on Google+Share on Google+

Conversion of Decimal to Binary in Java

Advertisement
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.

212Remainder
260
230
211
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[10];
		n = Integer.parseInt(args[0]);
		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

Advertisements

Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: July 25, 2013

Ask Questions?    Discuss: Conversion of Decimal to Binary in Java  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments
DMCA.com