Showing posts with label Java program to convert decimal to binary. Show all posts
Showing posts with label Java program to convert decimal to binary. Show all posts

How to Convert a Decimal Number to Binary Equivalent in Java

Write a Java program to convert the decimal number into the binary equivalent.




Java program to convert the decimal into binary


Decimal Number System - 

The decimal number system consists of digits from 0 to 9.


Binary Number System - 

The binary number system consists of only two digits which are 0 and 1. 


PROGRAM :


import java.util.Scanner;

public class DecimalBinary 

{

    public static void main(String args[])

    {

        int dec, q, i=1, j;

        int bin[] = new int[100];

        Scanner scan = new Scanner(System.in);

        System.out.print("Enter a Decimal Number : ");

        dec = scan.nextInt();

        q = dec;

        while(q != 0)

        {

            bin[i++] = q%2;

            q = q/2;

        }


       System.out.print("Equivalent Binary number is: ");

        for(j=i-1; j>0; j--)

        {

            System.out.print(bin[j]);

        }

        System.out.print("\n");

    }

}


Output:


Enter a Decimal Number : 45                                                                                    

Equivalent Binary number is: 101101  


Also read:

How to convert binary to decimal equivalent in Java?