Convert Binary to Decimal in Java

Here you will get program to convert binary to decimal in Java.

We can convert a binary number into decimal in two ways, using Integer.parseInt() method and by using your own logic.

Below I have shared program for both the methods.

Also Read: Convert Decimal to Binary in Java

Convert Binary to Decimal in Java

Method 1: Using Integer.parseInt()

We can directly use parseInt() method of Integer class for binary to decimal conversion.

import java.util.Scanner;

public class JavaB2D {
	public static void main(String args[]){
		int decimalNumber;
		String binaryNumber;
		Scanner sc = new Scanner(System.in);
		
		System.out.println("Enter a binary number:");
		binaryNumber = sc.nextLine();
		
		decimalNumber = Integer.parseInt(binaryNumber, 2);
		
		System.out.println("Decimal number is " + decimalNumber);
	}
}

Output

Enter a binary number:
11
Decimal number is 3

Method 2: Using Own Logic

This method goes like:

  1. Extract last digit from binary number by dividing with 10 using operator.
  2. Multiply this digit by 2n, where n starts from 0 and goes to (total digits in binary number) – 1.
  3. Do addition of each multiplication term.
  4. Remove last digit from binary number by dividing with 10 using operator.
  5. Repeat above steps until binary number does not become 0.

Example: 101 = 2* 1 + 2* 0 + 20 * 1 = 5

import java.util.Scanner;

public class JavaB2D {
	public static void main(String args[]){
		int binaryNumber, decimalNumber = 0, p = 0;
		Scanner sc = new Scanner(System.in);
		
		System.out.println("Enter a binary number:");
		binaryNumber = sc.nextInt();
		
		while(binaryNumber != 0){
			decimalNumber += binaryNumber%10 * Math.pow(2, p);
			binaryNumber /= 10;
			p++;
		}
		
		System.out.println("Decimal number is " + decimalNumber);
	}
}

Output

Enter a binary number:
1010
Decimal number is 10

Comment below if you have doubts or found any mistake in above programs.

Leave a Comment

Your email address will not be published. Required fields are marked *