DEV Community

Rajesh Mishra
Rajesh Mishra

Posted on • Originally published at onlinetutorials.tech on

Binary to Decimal Java How To Convert Binary To Decimal In Java

There are a multiple way to convert binary to decimal in Java:

Convert Binary To Decimal In Java Interger.parseInt() method:

This is really one of the simplest way in java to get Decimal number in java:

package com.onlinetutorials.tech;
public class ConvertBinaryToDecimalInJava {
       public static void main(String args[]){
              String binarynumber="10101";
              int decimalnumber=Integer.parseInt(binarynumber,2);
              System.out.println(decimalnumber);
       }
}

Output of above program after executions would be: 21.

Example:

package com.onlinetutorials.tech;
public class ConvertBinaryToDecimalInJava {
       public static void main(String args[]){
            System.out.println(Integer.parseInt("1110",2));
            System.out.println(Integer.parseInt("0010",2));
            System.out.println(Integer.parseInt("1010",2));
            System.out.println(Integer.parseInt("0110",2));
            System.out.println(Integer.parseInt("1101",2));
       }
}

Output of above program after executions would be:
14
2
10
6
13

Java program for Binary To Decimal using custom logic:

package com.onlinetutorials.tech;
public class ConvertBinaryToDecimalInJava {
       public static int retrieveDecimal(int binarynumber){
            int decimalnumber = 0;
            int power = 0;
            while(true){
                  if (binarynumber == 0){
                      break;
                  }else{
                      int temp = binarynumber%10;
                      decimalnumber += temp*Math.pow(2, power);
                      binarynumber = binarynumber/10;
                      power++;
                   }
            }
            return decimalnumber;
       }
       public static void main(String args[]){
            System.out.println("Decimal value is: "+retrieveDecimal(1110));
            System.out.println("Decimal value is: "+retrieveDecimal(0010));
            System.out.println("Decimal value is: "+retrieveDecimal(1010));
            System.out.println("Decimal value is: "+retrieveDecimal(0110));
            System.out.println("Decimal value is: "+retrieveDecimal(1101));
       }
}

Output of above program after executions would be:
14
8
10
16
13

You can visit onlinetutorials.tech for more Java Tutorials
Visit us for more tutorials:
Java Tutorial
Python Tutorial
RabbitMQ Tutorial
Spring boot Tutorial

Top comments (0)