# Java Program to Convert Binary Number to Decimal Number

• Write a program in Java to convert binary number to decimal number using Integer.parseInt method.
• Write a function in java to convert binary to decimal numbers.

We have to convert a binary number( base 2) to decimal number (base 10). Binary number system is a base 2 number system using digits 0 and 1 whereas Decimal number system is base 10 and using digits from 0 to 9. Given a binary number as input from user convert it to decimal number.

```Input Binary Number
0101
Decimal Number
5
```

## Java program to convert binary to decimal number using parseInt method

In this program, we will use parseInt method of Integer class to convert a binary number to decimal number.

static int parseInt(String s, int radix);
Above method of Integer class, parses the string argument as a signed integer in the radix specified by the second argument.
Arguments
• s : A number represented as a string.
• radix : Base(or Radix) of the input number used to convert String s into integer.
```package com.tcc.java.programs;

import java.util.*;

public class BinaryToDecimal {
public static void main(String args[]) {
String binary;
Scanner in = new Scanner(System.in);
System.out.println("Enter a Binary Number");
binary = in.nextLine();

System.out.println("Decimal Number : "+Integer.parseInt(binary,2));

}
}
```
Output
```Enter a Binary Number
1001
Decimal Number : 9
```

## Java program to convert binary to decimal using while loop

Algorithm to convert Binary to Decimal number
• We multiply each binary digit with 2i and add them, where i is the position of the binary digit(starting from 0) from right side. Least significant digit is at position 0.
Let's convert 0101 binary number to decimal number
Decimal number = 0*23 + 1*22 + 0*21 + 1*20 = 0 + 4 + 0 + 1 = 5
```package com.tcc.java.programs;

import java.util.*;

public class BinaryToDecimalTwo {
public static void main(String args[]) {
int num, decimal = 0, i=0;

Scanner in = new Scanner(System.in);
System.out.println("Enter a Binary Number");
String binary = in.nextLine();
num = Integer.parseInt(binary);

while(num != 0){
decimal += (num%10)*Math.pow(2, i);
num = num /10;
i++;
}

System.out.println("Decimal Number : "+ decimal);
}
}
```
Output
```Enter a Binary Number
100
Decimal Number : 4
```
```Enter a Binary Number
10101
Decimal Number : 21
```

Recommended Posts
 Java Program to Convert Decimal to Binary Numbers Java Program to Convert Octal Number to Decimal Number Java Program to Convert Celsius to Fahrenheit Java Program to Convert Fahrenheit to Celsius Java Program to Calculate Simple Interest Java Program to Calculate Compound Interest Java Program to Make a Simple Calculator using Switch Statement Java Program to Print Pascal Triangle Java Program to Print Right Triangle Star Pattern Java Program to Count Number of Digits in a Number Java Program to Reverse a Number using Recursion All Java Programs
 Previous Next