BigInteger conversion

In this chapter you will learn:

  1. How to convert BigInteger to double value
  2. How to convert BigInteger to byte array
  3. How to convert long type value to BigInteger

Convert BigInteger to double value

double doubleValue() Converts this BigInteger to a double.

import java.math.BigInteger;
/*from   j  a  v a  2 s .co  m*/
public class MainClass {
  public static void main(String[] args) {
    System.out.println("Here's Long.MAX_VALUE: " + Long.MAX_VALUE);
    BigInteger bInt = new BigInteger("3419229223372036854775807");
    System.out.println("Here's a bigger number: " + bInt);
    System.out.println("Here it is as a double: " + bInt.doubleValue());
  }

}

The output:

Convert BigInteger to byte array

byte[] toByteArray() Returns a byte array containing the two's-complement representation of this BigInteger.

import java.math.BigInteger;
import java.util.Arrays;
//j a  v  a 2 s  .c om
public class Main {
  public static void main(String[] argv) throws Exception {
    byte[]  bytes = new byte[] { 0x1, 0x00, 0x00 };
    BigInteger bi = new BigInteger(bytes);
    bytes = bi.toByteArray();
    System.out.println(Arrays.toString(bytes));
  }
}

The output:

Convert long type value to BigInteger

static BigInteger valueOf(long val) returns a BigInteger whose value is equal to that of the specified long.

import java.math.BigInteger;
/* j ava 2 s . c om*/
public class Main {
  public static void main(String[] argv) throws Exception {
    // Create via a string
    BigInteger bi1 = new BigInteger("1234567890123456890");

    // Create via a long
    BigInteger bi2 = BigInteger.valueOf(123L);

    bi1 = bi1.add(bi2);
    System.out.println(bi1);
  }
}

The output:

Next chapter...

What you will learn in the next chapter:

  1. How to Convert BigInteger to String
  2. How to convert BigInteger to String with given radix
Home » Java Tutorial » BigDecimal BigInteger

BigDecimal

    BigDecimal
    BigDecimal constants
    BigDecimal Rounding mode
    BigDecimal creation
    BigDecimal calculation
    BigDecimal convert
    BigDecimal Comparison
    BigDecimal to String
    BigDecimal decimal point
    BigDecimal precision
    BigDecimal format

BigInteger

    BigInteger class
    BigInteger creation
    BigInteger add, subtract, multiply and divide
    BigInteger power and modPow
    BigInteger conversion
    BigInteger to String
    BigInteger bit and,or,xor,test,flip,negate
    BigInteger bit shift left and right
    BigInteger prime value
    BigDecimal
    BigDecimal constants
    BigDecimal Rounding mode
    BigDecimal creation
    BigDecimal calculation
    BigDecimal convert
    BigDecimal Comparison
    BigDecimal to String
    BigDecimal decimal point
    BigDecimal precision
    BigDecimal format