Monday, January 4, 2021

Decimal To Binary And Hexadecimal Conversion

 

class Name: Number

 Member Variable: int n

 Member Methods:

 constructor: assigns 0 to n

 input (): accept value for n

 decttobin(): convert and display the binary equivalent of n

 dectohex(): convert and display the hexadecimal equivalent of n

 

 Write a menu driven program to perform the job

 1. decimal to binary

 2. decimal to hexadecimal     

 

import java.util.*;

class Number

{

int n;

Scanner sc=new Scanner(System.in);

Number()

{

     n=0;

}

void input()

{

    System.out.print("\nEnter the Number:");

    n=sc.nextInt();

    System.out.print("\nEnter 1 for Decimal to binary, 2 for decimal to hexa:");

    int c=sc.nextInt();

    switch(c)

    {

         case 1:

         decttobin();

         break;

         case 2:

         dectohex();

         break;

         default:

         System.out.print("\nWrong Choice:");

         System.exit(0);

        }

    }

    private void  decttobin()

    {

        String s="";

        int i;

        for(i=n;i>0;i=i/2)

        {

             s=s+i%2;

        }

        System.out.print("\nequivalent binary= ");

        for(i=s.length()-1;i>=0;i--)

        System.out.print(s.charAt(i));

    }

        private void  dectohex()

    {

        String s="";

        int i,d;

        for(i=n;i>0;i=i/16)

        {

             d=i%16;

             if(d<=9)

             s=s+d;

             else 

             s=s+ (char)(55+d);

             /* ASCII of A is 65, B is 66 and so on, so the remainder is added with 55 and the int value is

              converted into char to give the hexa digit               */

        }

        System.out.print("\nequivalent Hexadecimal= ");

        for(i=s.length()-1;i>=0;i--)

        System.out.print(s.charAt(i));

    }

public static void main(String args[])

{

     Number ob=new Number();

     ob.input();

    }

}


Other Programs On Numbers: CLICK HERE

No comments:

Post a Comment

Subscribe via email

Enter your email address:

Delivered by FeedBurner