Binary to decimal conversion using Java

Binary to decimal conversion

In this article we will discuss binary to decimal conversion using java. For this purpose we need to ask a binary number from user and convert that binary number to its decimal equivalent form and then print the converted number on to the screen.
For conversion, we multiply each digit of binary number from right with power of 2 and adding each multiplication result. The power starts from 0 and goes to p-1, where p is the total number of digits in binary number. For better understanding with an example just have a look towards the diagram shown at the right.

In number system, Binary number uses only two digits of 0, 1 which has base 2. Whereas Decimal Number uses only 10 Symbols: 0, 1, 2, 3, 4, 5, 6, 7 , 8 and 9 which has base 10.

For example:

100101 in base 2(Binary) => 37 in Base 10 (Decimal)

Binary to decimal conversion

Working :

Step 1 : Ask the user to enter a binary number.

Step 2 : Declare two variables, one for storing decimal value and second for storing value of the power.

Step 3 : Use  the while loop till binary number entered by user is greater than 0.

Step 4 : Use a statement to get the last digit of the binary number.

Step 5 : Use the statement for adding each digit by multiplying by the power of 2 and power starts with 0 till p-1 (where p is the number of digits in the binary number) by using power function.

Step 6 : Use the statement for removing last digit of the binary number and taking only remaining number and increase the value of the power by 1.

Step 7 : Repeat the steps 3 to 6 till the value of the loop does not gets false. 

Step 8 : Print the result.

Binary to decimal conversion using java

Code in for Binary to decimal conversion using java:

//Java program to convert Binary number to decimal number
import java.util.Scanner;
public class Binary_To_Decimal
public static void main(String args[])
Scanner sc = new Scanner(;
System.out.print("Enter a binary number : ");
int binary = sc.nextInt();
//Declaring variable to store decimal number
int decimal = 0;
//Declaring variable to use in power
int n = 0;
//writing logic for the conversion
while(binary > 0)
int temp = binary%10;
decimal += temp*Math.pow(2, n);
binary = binary/10;
System.out.println("Decimal number : "+decimal);
//closing scanner class(not compulsory, but good practice)

Output :

Enter a binary number : 111001
Decimal number : 57

Time and Space Complexities


Time Complexity – O(K), where K is the count of the digits in the binary number

Space Complexity – O(1)