How to convert binary to decimal in Java?

Ads
 

How to convert binary to decimal in Java?

Let's learn to convert binary to decimal in Java.

Let's learn to convert binary to decimal in Java.

How to convert binary to decimal in Java program?

In this section we are going to convert a binary number to it decimal representation. In our program we have defined a binary number in string format and then converting it to a decimal number.

The java.lang package provides the function to convert the integer data into the binary to decimal.

Here is the code that we are using:

int i= Integer.parseInt(str,2);

Above method concerts Binary to Decimal in Java.

Computer is based on the binary number format and it just know 0 or 1. So, in this example we are converting binary value to decimal value in Java.

Code Description:

The parseLong() method is used to convert Binary to Decimal in our program.

Here is the code of this program:

package net.roseindia;

public class BinayToDecimalExample {

	public static void main(String[] args) {
		String str = "10010";
		long num = new Long(str);
		long rem;
		while(num>0){
			rem = num % 10;
			num = num/10;
			if(rem != 0 && rem !=1){	
			System.out.println("Not a binary number");
			System.exit(0);
			}

		}
		int i= Integer.parseInt(str,2);
		System.out.println("Decimal:="+ i);		
	}

}

Output of this program:

Decimal:=18

In this tutorial you learned to convert Binary to Decimal using the function Integer.parseInt(str,2). We have many tutorials of converting one data format into another in Java. You can view all these tutorials by visiting following on our website.

Check more tutorials at: Java Conversion examples.

Ads

Ads