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

In this Java program, we will learn how to find the GCD of two numbers using Java.  GCD (Greatest Common...
  • Java
  • December 3, 2024
In this Java Program, you’ll learn how to swap two numbers using the Java programming language.  How to Swap Two...
  • Java
  • December 2, 2024
In this Java program , we will learn how to Find Largest Element in an Array in your Java program.   How to Find Largest Element...
  • Java
  • December 2, 2024