Signup/Sign In

How to convert Java Binary to Decimal

In Java, Binary can be converted into Decimal by using Integer.parseInt() method and custom code created by your own. Let's see the examples.

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 binary strings are converted into decimal values. This example is useful if binary is of string type or we can convert the value into string first and then apply parseInt() method. See the example below.

public class Studytonight
{    
	public static void main(String args[])
	{    
		String b1 = "111010";
		String b2 = "11001010";
		String b3 = "1110";

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

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


Decimal value is : 58
Decimal value is : 202
Decimal value is : 14

Example 2:

If you don't want to use any built-in method then use this custom code that will convert the binary value to the decimal. See the example below.

public class CoreJava
{    
	public static int decimalconvt(int bin)
	{  
		int dec = 0;  
		int n = 0;  

		while(true)
		{  
			if(bin == 0)
			{  
				break;  
			}
			else 
			{  
				int t = bin % 10;  
				dec+= t * Math.pow(2, n);  
				bin = bin/10;  
				n++;  
			}  
		}  
		return dec;
	}
	public static void main(String args[])
	{    
		System.out.println("Decimal of 1010001 is: "+decimalconvt(1010001));  
		System.out.println("Decimal of 1010110 is: "+decimalconvt(1010110));  
		System.out.println("Decimal of 11111011 is: "+decimalconvt(11111011));  
	}    
}


Decimal of 1010001 is: 81
Decimal of 1010110 is: 86
Decimal of 11111011 is: 251



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.