How to Convert Hex to Decimal in Java

0 min read 137 words

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);
  }
  
}
Tags:
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags