decimal to binary

In this article we are going to see how we can convert decimal to binary. We also write java code to convert decimal to binary.

Decimal to Binary conversion:-

For conversion of Decimal to Binary continuously divide the decimal number by 2 until decimal number become 0. and add every reminder after division at the beginning of the result variable.


Let’s assume Decimal =5

  • Step-1 : decimal = 5/2 =2 , reminder = 1 , result= 1
  • Step-2 : decimal =2/2=1,reminder=0 ,result=01
  • Step-3 : decimal =1/2=0,reminder=1 , result=101

Now Decimal become 0 hence the final result is 101, Which is binary conversion of 5.

Steps for code to convert decimal to binary:-

  • Create a string variable to store binary value.
  • Run a loop while decimal number is greater than 0.
  • calculate the reminder dividing by 2 i.e. reminder = number%2.
  • Add the beginning of result string.
  • Divide number by 2 i.e. number = number/2.
  • End of loop.
  • The string variable will hold binary value of given decimal number.

Java code to convert decimal to binary:-

package gangforcode;
import java.util.*;
public class DecToBin {
 public static void decToBin(int n) {
	 String binary="";
	 while(n>0) {
	public static void main(String[] args) {
		Scanner sc = new Scanner(;
		System.out.println("Enter the Decimal number");
	    int n=sc.nextInt();




Decimal to binary

The same logic can be used to convert decimals to binary in other programing languages like C, C++, Python, etc.

Leave a Comment