Program on Decimal to Binary Number Conversion

Write a Program in Java to input a number in Decimal number system and convert it into its equivalent number in the Binary number system.
Note: Binary Number system is a number system which can represent a number in any other number system in terms of 0 and 1 only. This number system consists of only two basic digits i.e. 0 and 1.
For Example: 25 in the Decimal number system can be represented as 11001 in the Binary number system.
decimal to binary conversion

import java.io.*;
class Dec2Bin
{
    public static void main(String args[])throws IOException
    {
        BufferedReader br=new BufferedReader (new InputStreamReader(System.in));
        System.out.print("Enter a decimal number : ");
        int n=Integer.parseInt(br.readLine());
 
        int r;
        String s=""; //variable for storing the result
 
        char dig[]={'0','1'}; //array storing the digits (as characters) in a binary number system
 
        while(n>0)
            {
                r=n%2; //finding remainder by dividing the number by 2
                s=dig[r]+s; //adding the remainder to the result and reversing at the same time
                n=n/2;
            }
        System.out.println("Output = "+s);
    }
}

Output:

Enter a decimal number : 25
Output = 11001
Enter a decimal number : 47
Output = 101111
Enter a decimal number : 6
Output = 110

No comments:

Post a Comment