繁体   English   中英

我正在尝试将int转换为BigInteger,有人可以帮助我吗?

[英]I'm trying to convert int to BigInteger can someone help me?

我正在尝试制作一个将值转换为位的程序。 一切正常,直到我达到GB(GB)。 因此,例如1 GB应该等于80亿位,但结果却给了我一个否定的答案。 这是我的代码,有人可以给我一些启示吗?

else if(line.equals("GB")) {
        Scanner num = new Scanner(System.in);
        System.out.println("How many GigaBytes are you transfering to bits?");
        int number = num.nextInt();
        //int ans = number * 8 * 1000000000;
        BigInteger bigAns = BigInteger.valueOf(number * 8 * 1000000000);
        System.out.println(number + " GigaByte(s) equals " + bigAns + " bits.");
    }

这是我得到的输出:1 GB等于-589934592位。

在整个计算过程中使用BigInteger并不是一件坏事。 这样,在将这些数字相乘时,您不会冒溢出的风险。

BigInteger bigAns = BigInteger.valueOf(number).multiply(BigInteger.valueOf(8))
                              .multiply(BigInteger.valueOf(1000000000L));

您得到一个负数,因为您超出了有符号的32位整数的最大可能值,并导致溢出。

当处理这样的大数时,应该改用long ,它可以容纳更大的数。

为此, int ans = number * 8 * 1000000000更改为long ans = number * 8 * 1000000000l

您得到的答案是垃圾值。 您可以这样做,将int转换为BigInteger:

BigInteger bi = BigInteger.valueOf(myInteger.intValue());

正如Bohsulav所说:

您可以使用此数字* 8 * 1000000000l来防止溢出。

有帮助吗 让我知道 :)

首先转换为biginteger, 然后执行计算。

BigInteger.valueOf(number * 8 * 1000000000);

在这里,您以int进行计算,然后为时已晚 ,然后转换为BigInteger。

使用BigInteger.valueOf(number),然后调用适当的方法来执行计算。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM