Signup/Sign In

How to convert Java Hexadecimal to Decimal

In Java, Hexadecimal can be converted into Decimal either by using Integer.parseInt() method or custom Logic.

1. Integer.parseInt() Method

The parseInt() method is a part of Integer class which converts the string into an int in accordance with the specified radix.

Example 1:

Here, the hexadecimal strings are converted into decimal values. This method is useful when we have data in string format. It means if you want to use parseInt() method then first convert the data into string and then get decimal value.

public class StudyTonight
{    
	public static void main(String args[])
	{    
		String b1 = "78F";
		String b2 = "-56578D";
		String b3 = "996B";

		int d1 = Integer.parseInt(b1,16);
		int d2 = Integer.parseInt(b2,16);
		int d3 = Integer.parseInt(b3,16);

		System.out.println("Decimal value is : " +d1);
		System.out.println("Decimal value is : " +d2);
		System.out.println("Decimal value is : " +d3);
	}    
}


Decimal value is : 1935
Decimal value is : -5658509
Decimal value is : 39275

Example 2:

If you don't want to use any built-in method then use this custom code to convert hexadecimal values into decimals using custom logic. See the example below.

public class StudyTonight
{    
	public static int decimalconvt(String hexadec)
	{  
		String seq = "0123456789ABCDEF";  
		hexadec = hexadec.toUpperCase();  
		int val = 0;  
		for (int i = 0; i < hexadec.length(); i++)  
		{  
			char ch = hexadec.charAt(i);  
			int d = seq.indexOf(ch);  
			val = 16*val + d;  
		}  
		return val;  
	}
	public static void main(String args[])
	{    
		System.out.println("Decimal of 101D is: " +decimalconvt("101D"));  
		System.out.println("Decimal of 156F is: " +decimalconvt("17856D")); 
		System.out.println("Decimal of -17BAED is: " +decimalconvt("-17BAED")); 
	}    
}


Decimal of 101D is: 4125
Decimal of 156F is: 1541485
Decimal of -17BAED is: -15222035



About the author:
A Computer Science and Engineering Graduate(2016-2020) from JSSATE Noida. JAVA is Love. Sincerely Followed Sachin Tendulkar as a child, M S Dhoni as a teenager, and Virat Kohli as an adult.