Convert Binary to Decimal

In this section, you will learn how to convert a binary number into a decimal number.

Convert Binary to Decimal

In this section, you will learn how to convert a binary number into a decimal number.

Convert Binary to Decimal

Convert Binary to Decimal

     

In this section, you will learn how to convert  binary number  into a decimal number. The java.lang package provides the facility to convert the integer data into the binary to decimal. 

Code Description:

In this program, you will learn the use of parseLong() method.  Define a class "BinaryToDecimal" using the  parseLong() method. This method is used to parse the string argument as a signed decimal long. This method has been used for converting a long to a string and a String to a long.

Here is the code of this program:

import java.lang.*;
import java.io.*;

public class BinaryToDecimal{
  public static void main(String[] argsthrows IOException{
  BufferedReader bf= new BufferedReader(new InputStreamReader(System.in));
  System.out.print("Enter the Binary value: ");
  String str = bf.readLine();
  long num = Long.parseLong(str);
  long rem;
  while(num > 0){
  rem = num % 10;
  num = num / 10;
  if(rem != && rem != 1){
  System.out.println("This is not a binary number.");
  System.out.println("Please try once again.");
  System.exit(0);
  }
  }
  int i= Integer.parseInt(str,2);
  System.out.println("Decimal:="+ i);
  }
}

Download this program.

Output of this program:

C:\corejava>java BinaryToDecimal
Enter the Binary value:
10010
Decimal:=18
C:\corejava>_