Convert Hexadecimal to Decimal in Java

In one of the previous posts, we covered the conversion of a Decimal to Hexadecimal. Here, you will learn how to convert Hexadecimal to Decimal in Java. We will explore the following ways:

  • Using the parseInt() method
  • Using custom logic

Convert Hexadecimal to Decimal in Java using the parseInt() method

Integer class has a static method parseInt(String s, int radix) that parses the String argument as a signed integer in the radix specified by the second argument.

Example

class Test {

  public static void main(String[] args) {

    System.out.println(Integer.parseInt("f", 16));
    System.out.println(Integer.parseInt("a", 16));
    System.out.println(Integer.parseInt("240", 16));
  }
}
Output: 15 10 576

Parse Hexadecimal to Decimal using custom logic

There is always a way without using predefined methods, like in the following example:

public class Test {

  public static void main(String[] args) {

    System.out.println(getDecimal("f"));
    System.out.println(getDecimal("a"));
    System.out.println(getDecimal("240"));
  }

  public static int getDecimal(String hexString) {
    String digits = "0123456789ABCDEF";
    hexString = hexString.toUpperCase();
    int value = 0;

    for (int i = 0; i < hexString.length(); i++) {
      char c = hexString.charAt(i);
      int d = digits.indexOf(c);
      value = 16 * value + d;
    }

    return value;
  }
}
Output: 15 10 576
 
Happy coding!

Leave a Reply

Your email address will not be published. Required fields are marked *