Coding Lab - TechOnTechnology

Java program to convert a decimal number to binary.




import java.io.*;

import java.lang.*;

class decitobin
{

public static void main(String args[])throws IOException
{

int num,rem,deci,a,b,d,c,f=0,bin;

double i,power;
DataInputStream in=new DataInputStream(System.in);

while ( f == 0 )

{

System.out.println("\nENTER YOUR CHOICE  :\n");

System.out.println("1. BINARY TO DECIMAL.\n");

System.out.println("2. DECIMAL TO BINARY \n");

System.out.println("3. EXIT \n");

c=Integer.parseInt(in.readLine());

switch(c)
{
case 1:           
        System.out.println();
        System.out.println("ENTER A VALID BINARY NUMBER  :\n");

                num=Integer.parseInt(in.readLine());

                d=num;
        deci=0;
        i=0;  

                while( num > 0 )

                {

                a=num;

                num = num/10;

                rem= a%10;

                power=Math.pow(2,i);

                int x;

                x=(int)power;

                b=rem*x;

                deci=deci+b;

                i=i+1;

                }

                System.out.println("\nTHE DECIMAL EQUIVALENT OF "+d+" IS "+deci);

              break;
case 2:

        bin=0;
        i=0;
        System.out.println();
                System.out.println("\nENTER DECIMAL NUMBER  :\n");

                num=Integer.parseInt(in.readLine());

                d=num;

                while( num > 0 )

                {

                a=num;

                num = num/2;

                rem= a%2;

                power=Math.pow(10,i);

                int x;

                x=(int)power;

                b=rem*x;

                bin=bin+b;

                i=i+1;

                }

                System.out.println("\nTHE BINARY EQUIVALENT OF "+d+" IS "+bin);

        break;
case 3:            f=1;
        break;
default :       System.out.println("\nINVALID OPTION \n");

}

}

}

}

Name

Email *

Message *