Java Program to Convert Binary Number to Decimal and vice-versa

In this Java program, you’ll learn how to Convert Binary Number to Decimal and vice-versa using the Java programming language.  

How to Convert Binary Number to Decimal and vice-versa using JAVA? 

Example 1: Using custom method 

RUN CODE SNIPPET
class Main  
{ 
  public static void main(String[] args)  
  { 
    long num = 11110111; 
    int decimal = convertBinaryToDecimal(num); 
    System.out.println("Binary to Decimal"); 
    System.out.println(num + " = " + decimal); 
  } 
  public static int convertBinaryToDecimal(long num) 
   { 
    int decimalNumber = 0, i = 0; 
    long remainder; 
    while (num != 0)  
    { 
      remainder = num % 10; 
      num /= 10; 
      decimalNumber += remainder * Math.pow(2, i); 
      ++i; 
    } 
    return decimalNumber; 
  } 
}

OUTPUT: 

Binary to Decimal 

11110111 = 247

Example 2: Using ParesInt() 

RUN CODE SNIPPET
class Main 
{ 
  public static void main(String[] args)  
  { 
    String binary = "01011111"; 
    int decimal = Integer.parseInt(binary, 2); 
    System.out.println(binary + " in binary = " + decimal + " in decimal."); 
  } 
}

OUTPUT: 

01011111 in binary = 95 in decimal.

Share:

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

Java is a popular programming language that is used to develop a wide range of applications. If you are a...
  • Java
  • March 6, 2023
Java is a programming language and computing platform that is used to create various types of applications. It is used...
  • Java
  • March 6, 2023
In this post, you’ll learn how to download and install JUnit in Eclipse so that you can use in your...
  • Java
  • October 9, 2022