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