Sunday, 8 April 2012

Convert Octal to Decimal in Java

In this section, you will learn to change octal 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 octal number to decimal number example.
 **/

import java.math.BigInteger;

public class ConvertOctalToDecimalExample {

    public static void main(String args[]) {

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

        String int_octal = "4764544";
        int int_decimal = Integer.parseInt(int_octal, 8);
        System.out.println("decimal equivalent of 4764544 = " + int_decimal);

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

        String long_octal = "5764544576477";
        long long_decimal = Long.parseLong(long_octal, 8);
        System.out.println("decimal equivalent of 5764544576477  = "
                + long_decimal);

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

        String big_octal = "76757645445764774676457";
        BigInteger big_decimal = new BigInteger(big_octal, 8);
        System.out.println("decimal equivalent of 76757645445764774676457 = "
                + big_decimal);

    }

}

The output is

decimal equivalent of 4764544 = 1304932
decimal equivalent of 5764544576477  = 410799766847
decimal equivalent of 76757645445764774676457 = 580781026369888025903

No comments:

Post a Comment