Friday, January 20, 2012

How to convert BigInteger to int in java



import java.math.BigInteger;
class ConvertBig
    {
    public static void main(String arg[])
        {
        BigInteger big= new BigInteger("1234");
        System.out.println("Value of BigInteger big= " + big);    
        int i = big.intValue();
        System.out.println("Value of Integer i= " + i);
        }
    }



This program shows how to convert a BigInteger value to an integer value in java. the program convertsthe value in 'big' which is aBigInteger variable to an integer variable 'i'.
Save program as ConvertBig.java

5 comments :

  1. If big is larger than an int can hold you will get unexpected results.

    ReplyDelete
  2. BigInteger a = new BigInteger("14505235153");
    BigInteger b = new BigInteger("69");
    BigInteger l=a.add(b);

    System.out.println(l+" "+l.intValue());


    == wrong answer

    ReplyDelete