Java convert hex to decimal

In this post we are going to learn java convert hex to decimal.

java convert hex to decimal

In hexadecimal to decimal java program we are using Integer.parseInt method. This method parses string argument as a signed integer in the radix specified by the second argument. Here’s the syntax,

Also read – decimal to hexadecimal java program

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

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


Similarly we can use method to convert hex to decimal,

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:

Decimal value of b is : 11
Decimal value of d is : 13
Decimal value of 151 is : 337

Related Posts