Sunday 8 April 2012

Convert Hexadecimal to Decimal in Java

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

import java.math.BigInteger;

public class ConvertHexToDecimalExample {

    public static void main(String args[]) {

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

        String int_hex = "45fd";
        int int_decimal = Integer.parseInt(int_hex, 16);
        System.out.println("decimal equivalent of 45fd = " + int_decimal);

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

        String long_hex = "56fde67894b";
        long long_decimal = Long.parseLong(long_hex, 16);
        System.out.println("decimal equivalent of 56fde67894b = "
                + long_decimal);

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

        String big_hex = "89574665cc34f01ea";
        BigInteger big_decimal = new BigInteger(big_hex, 16);
        System.out.println("decimal equivalent of 89574665cc34f01ea= "
                + big_decimal);

    }

}


The output is

decimal equivalent of 45fd = 17917
decimal equivalent of 56fde67894b = 5978030836043
decimal equivalent of 89574665cc34f01ea= 158343297747225870826

No comments:

Post a Comment