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:
- Extract last digit from binary number by dividing with 10 using % operator.
- Multiply this digit by 2n, where n starts from 0 and goes to (total digits in binary number) – 1.
- Do addition of each multiplication term.
- Remove last digit from binary number by dividing with 10 using / operator.
- Repeat above steps until binary number does not become 0.
Example: 101 = 22 * 1 + 21 * 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.