Java Program to Convert Decimal to Binary Numbers

Here is a Java program to convert decimal number to binary number. In this java program, we will take a decimal number as input from user and then convert it to binary number. Before jumping into java program, here is the brief introduction of binary and decimal number systems.

  • Binary number system is base 2 number system and uses 0 and 1 digits. For Example: 0, 1, 01, 101, 1101
  • Decimal number system is a base 10 number system using digits for 0 to 9. For Example: 6, 3, 12, 10, 123
Algorithm to convert decimal to binary number
  • Divide the input decimal number by 2 and store the remainder.
  • Store the quotient back to the input number variable.
  • Repeat this process till quotient becomes zero.
  • Equivalent binary number will be the remainders in above process in reverse order.

Suppose input decimal number is 12
Step 1. 12/2 , Remainder = 0, Quotient = 6
Step 2. 6/2 , Remainder = 0, Quotient = 3
Step 3. 3/2 , Remainder = 1, Quotient = 1
Step 4. 1/2 , Remainder = 1, Quotient = 0
Now, the Binary equivalent of 12 is the remainders in reverse order : 1100


Java Program to convert Decimal to Binary Number

package com.tcc.java.programs;

import java.util.Scanner;

public class DecimalToBinary {
    public static void main(String[] args) {
        long dec;
        Scanner scanner;
        scanner = new Scanner(System.in);
        System.out.println("Enter a Decimal Number");
        dec = scanner.nextLong();

        // Calling decimalToBinary method to convert decimal
        // number to binary
        System.out.println("Binary Number : " + decimalToBinary(dec));
    }


    public static long decimalToBinary(long n) {
        long remainder, binary = 0, i = 1;

        while (n != 0) {
            remainder = n % 2;
            n = n / 2;
            binary = binary + (remainder * i);
            i = i * 10;
        }
        return binary;
    }
}
Output
Enter a Decimal Number
20
Binary Number : 10100
Enter a Decimal Number
16
Binary Number : 10000

Recommended Posts
Java program to convert binary number to decimal number
Java Program to Convert Fahrenheit to Celsius
Java Program to Calculate Simple Interest
Java Program to Calculate Compound Interest
Java Program to Make a Simple Calculator using Switch Statement
Java Program to Print Pascal Triangle
Java Program to Convert Octal Number to Decimal Number
Java Program to Convert Celsius to Fahrenheit
Java Program to Print Right Triangle Star Pattern
Java Program to Count Number of Digits in a Number
Java Program to Reverse a Number using Recursion
All Java Programs