on Leave a Comment

Java Program to Convert Hexadecimal to Decimal

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

We can convert hexadecimal to decimal by two ways:

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

Java Program to Convert Hexadecimal to Decimal Using Integer Class

import java.util.Scanner;
public class HexToDec
{
 public static void main(String[] args) {
 String hex;
        Scanner kb = new Scanner(System.in);
  
        System.out.print("Enter Hexadecimal Number : ");
        hex = kb.nextLine();
        System.out.println("\nConverting...\n");
        Integer dec = Integer.parseInt(hex, 16);
        System.out.print("Decimal Equivalent is " + dec);
 }
}

Output:

Enter Hexadecimal Number : B1

Converting...

Decimal Equivalent is 177

Java Program to Convert Hexadecimal to Decimal without Using Integer Class

import java.util.Scanner;

public class HexToDec
{
    public static void main(String args[])
    {
        String hex;
        int dec = 0;
        Scanner kb = new Scanner(System.in);
  
        System.out.print("Enter Hexadecimal Number : ");
        hex = kb.nextLine();
  
        String digits = "0123456789ABCDEF";
        hex = hex.toUpperCase();
        System.out.println("\nConverting...\n");
        for (int i = 0; i < hex.length(); i++)
        {
          char ch = hex.charAt(i);
          int d = digits.indexOf(ch);
          dec = 16*dec + d;
        }
        System.out.print("Decimal Equivalent is " + dec);
    }
}

Output:

Enter Hexadecimal Number : A8

Converting...

Decimal Equivalent is 168



0 comments:

Post a Comment