Home Java Java-conversion Convert Binary to Decimal



Convert Binary to Decimal
Posted on: May 31, 2007 at 12:00 AM
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  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>_

Related Tags for Convert Binary to Decimal:
javacideclassdatabinaryconvertparseintegermethodvidecimalusingintthisidpackagedefinelongprogramtolearnramcilcilanearbieilitdesliuseiminasmntparjpackclesagemeintoproackbinsatpackislleaarrtvassthavfinprodeonogro


More Tutorials from this section

Ask Questions?    Discuss: Convert Binary to Decimal   View All Comments

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.