Java convert hex to decimal

Let’s learn java convert hex to decimal.

Java convert hex to decimal

Write a java program that converts a hexadecimal number to a decimal number is one of the frequently asked java program interview question.

In java hexadecimal to decimal conversion we are using Integer.parseInt method.

Also read – octal to decimal in java

Integer.parseInt() method parses string argument as a signed integer in the radix specified by the second argument.

Here’s the syntax,

public static int parseInt(String s,int radix) throws NumberFormatException

In the below java program we have to convert given hexadecimal number ‘strHex’ into decimal number using Integer.parseInt() method and passing base 16.

Let’s see program for hexadecimal to decimal,

public class FB
{ 
   public static void main(String[] args)
   { 
      String strHex = "b"; 
      int decimal = Integer.parseInt(strHex, 16); 
      System.out.println("Decimal number : " + decimal);
   }
}



Output:

Decimal number : 11


Hexadecimal to decimal java user input

Meanwhile to we can convert hexadecimal to decimal in java based on user input. For this we need Scanner class.

Logic to convert a hexadecimal to a decimal number is same as above java program.

Now let’s see java program,

import java.util.Scanner;

public class HexToDecimalDemo 
{
   public static void main(String[] args) 
   {
      Scanner sc = new Scanner(System.in);
      System.out.print("Please enter hexadecimal number: ");
      String strHexNumber = sc.nextLine();    
      // converting hexadecimal to decimal by passing base 16 
      int decimalNumber = Integer.parseInt(strHexNumber, 16);
      System.out.println("Converting hexadecimal to decimal: " + decimalNumber);
      sc.close();
   }
}


Output:

Please enter hexadecimal number: 6A
Converting hexadecimal to decimal: 106

Similarly we can convert a hexadecimal to a decimal number using user defined method,

public class HexaToDecimal
{
   public static int convertHexadecimal(String str)
   {
      String strHexa = "0123456789ABCDEF";
      str = str.toUpperCase();
      int value = 0;
      for(int a = 0; a < str.length(); a++)
      {
         char ch = str.charAt(a);
         int d = strHexa.indexOf(ch);
         value = 16 * value + d;
      }
      return value;
   }

   public static void main(String[] args)
   {
      System.out.println("Decimal value of b is : " + convertHexadecimal("b")); 
      System.out.println("Decimal value of d is : " + convertHexadecimal("d")); 
      System.out.println("Decimal value of 151 is : " + convertHexadecimal("151"));
   }
}



Output:

java convert hex to decimal