How to Convert Hex to Decimal in Java

The challenge

Write a function that converts an input string contains a hex value, and return a decimal.

Test cases

import org.junit.Test;
import static org.junit.Assert.*;

public class ExampleTests {

  @Test
  public void examples() {
      // assertEquals("expected", "actual");
      assertEquals(1, ConvertHexToDec.hexToDec("1"));
      assertEquals(10, ConvertHexToDec.hexToDec("a"));
      assertEquals(16, ConvertHexToDec.hexToDec("10"));
      assertEquals(255, ConvertHexToDec.hexToDec("FF"));
      assertEquals(-12, ConvertHexToDec.hexToDec("-C"));
  }
  
}

The solution in Java

In Java, it is really easy to convert Hex to Decimal.

You simply use the Integer class and call the parseInt method, making sure to also provide the base that you want to convert from.

As we know that the input will be a hex value, and we also know that the hexadecimal number system is a base 16 numbering system, we are able to do the following:

public class ConvertHexToDec {

  public static int hexToDec(final String hexString) {
    return Integer.parseInt(hexString, 16);
  }
  
}