Monday, 9 April 2012

Convert Binary to Decimal in Java

In this section, you will learn to change binary number into decimal.

Integer wrapper class offers Integer.parseInt(String s,int radix) method to convert binary ,octal and hex number to decimal number.Here parameter s is the string form of the binary,octal or hex number, and int radix, which indicates in what base (for example binary, octal, or hexadecimal) the first argument is represented.

The method Integer.parseInt(String s,int radix) can be used only for the numbers whose size is less than 32 bits.The method throws unchecked run-time exception, java.lang.NumberFormatException  when it is applied for numbers whose size greater than 32 bits.

Long wrapper class also offers Long.parseLong(String s,int radix) method which you can use to convert binary,octal and hex numbers to decimal numbers.This method supports numbers with size less than 64 bits.

Use java.math.BigInteger class, when you need to convert binary,octal and hex numbers with size greater than 64 bits.

For example:
/**
 * Convert binary number to decimal number example.
 **/

import java.math.BigInteger;

public class ConvertBinaryToDecimalExample {

 public static void main(String args[]) {

/** If the input binary number is < 32 bits **/

String int_binary = "101101";
int int_decimal = Integer.parseInt(int_binary, 2);
System.out.println("decimal equivalent of 101101 = " + int_decimal);

/** If the input binary number is < 64 bits **/

String long_binary = "11111011101101101101110111011101";
long long_decimal = Long.parseLong(long_binary, 2);
System.out.println("decimal equivalent of 11111011101101101101110111011101  = "
    + long_decimal);

/** If the input binary number is >64 bits **/

String big_binary = "1111111111111111111111111111111111111011101101101101110111011101";
BigInteger big_decimal = new BigInteger(big_binary, 2);
System.out.println("decimal equivalent of 1111111111111111111111111111111111111011101101101101110111011101 = "
    + big_decimal);

 }

}

The output is

decimal equivalent of 101101 = 45
decimal equivalent of 11111011101101101101110111011101  = 4223065565
decimal equivalent of 1111111111111111111111111111111111111011101101101101110111011101 = 18446744073637649885

No comments:

Post a Comment