on Leave a Comment

Java Program to Convert Decimal to Hexadecimal

This java program converts decimal value to hexadecimal value. First, user has to enter a decimal number, then we have to convert decimal value to hexadecimal value and finally displayed on the screen.

Hexadecimal Numerals: Hexadecimal is a base-16 number system. It uses 16 symbols, the symbols 0–9 to represent values zero to nine, and A,B,C,D,E,F (or alternatively a, b, c, d, e, f) to represent values ten to fifteen.

We can convert decimal to hexadecimal by two ways:

- Using built-in method (toHexString() method of Integer class)
- Without using built-in method

Java Program to Convert Decimal to Hexadecimal Using toHexString() Method

import java.util.Scanner;
class DecToHex
{
    public static void main(String args[])
    {
      Scanner scan = new Scanner(System.in);
      System.out.print("Enter Decimal Number : ");
      int dec = scan.nextInt();
        
      System.out.println("\nConverting...\n");
      String hex = Integer.toHexString(dec);
      System.out.println("Equivalent Hexadecimal is "+hex);
    }
}


Output:

Enter Decimal Number : 59

Converting...

Equivalent Hexadecimal is 3b

Java Program to Convert Decimal to Hexadecimal without Using Built-in Method

import java.util.Scanner;
class DecToHex
{
   public static void main(String args[])
   {
     Scanner scan = new Scanner( System.in );
     System.out.print("Enter Decimal number : ");
     int dec = scan.nextInt();
     int rem;
     String disp=""; 

     // Digits in hexadecimal number system
     char hex[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
     System.out.println("\nConverting...\n");
     while(dec!=0)
     {
       rem = dec%16; 
       disp = hex[rem]+disp; 
       dec = dec/16;
     }
     System.out.println("Equivalent Hexadecimal is "+disp);
  }
}


Output:


Enter Decimal number : 61

Converting...

Equivalent Hexadecimal is 3D



0 comments:

Post a Comment