📜  Java中的 BigInteger longValue() 方法

📅  最后修改于: 2022-05-13 01:55:13.775000             🧑  作者: Mango

Java中的 BigInteger longValue() 方法

Java.math.BigInteger.longValue()将此 BigInteger 转换为 long 值。如果此函数返回的值太大而无法放入 long 值,则它将仅返回低位 64 位。这种转换可能会丢失有关 BigInteger 值整体大小的信息。该方法也可以返回符号相反的结果。

句法:

public long longValue()

返回:该方法返回一个 long 值,该值表示此 BigInteger 的 long 值。

例子:

Input: BigInteger1=3214558191
Output: 3214558191
Explanation: BigInteger1.longValue()=3214558191.

Input: BigInteger1=32145535361361525377
Output: -4747952786057577855
Explanation: BigInteger1.longValue()=-4747952786057577855. This BigInteger is too big for 
longValue so it is returning lower 64 bit.

示例 1:下面的程序说明 BigInteger 类的 longValue() 方法

// Java program to demonstrate longValue() method of BigInteger
  
import java.math.BigInteger;
  
public class GFG {
  
    public static void main(String[] args)
    {
  
        // Creating 2 BigInteger objects
        BigInteger b1, b2;
  
        b1 = new BigInteger("3214553537");
        b2 = new BigInteger("76137217351");
  
        // apply longValue() method
        long longValueOfb1 = b1.longValue();
        long longValueOfb2 = b2.longValue();
  
        // print longValue
        System.out.println("longValue of "
                           + b1 + " : " + longValueOfb1);
        System.out.println("longValue of "
                           + b2 + " : " + longValueOfb2);
    }
}
输出:
longValue of 3214553537 : 3214553537
longValue of 76137217351 : 76137217351

示例 2:当 return long 对于 long 值来说太大时。

// Java program to demonstrate longValue() method of BigInteger
  
import java.math.BigInteger;
  
public class GFG {
  
    public static void main(String[] args)
    {
        // Creating 2 BigInteger objects
        BigInteger b1, b2;
  
        b1 = new BigInteger("32145535361361525377");
        b2 = new BigInteger("7613721535372632367351");
  
        // apply longValue() method
        long longValueOfb1 = b1.longValue();
        long longValueOfb2 = b2.longValue();
  
        // print longValue
        System.out.println("longValue of "
                           + b1 + " : " + longValueOfb1);
        System.out.println("longValue of "
                           + b2 + " : " + longValueOfb2);
    }
}
输出:
longValue of 32145535361361525377 : -4747952786057577855
longValue of 7613721535372632367351 : -4783767069412450057

参考:
BigInteger longValue() 文档