[英]I'm trying to convert int to BigInteger can someone help me?
I'm trying to make a program that converts values to bits. 我正在尝试制作一个将值转换为位的程序。 Everything worked well till I got to GB(gigabytes). 一切正常,直到我达到GB(GB)。 So for instance 1 GB should equal 8 billion bits but the result is giving me a negative answer. 因此,例如1 GB应该等于80亿位,但结果却给了我一个否定的答案。 Here is my code can someone give me some insight? 这是我的代码,有人可以给我一些启示吗?
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.");
}
Here is the output I'm getting: 1 GigaByte(s) equals -589934592 bits. 这是我得到的输出:1 GB等于-589934592位。
It wouldn't be a bad thing to use BigInteger
throughout your calculations. 在整个计算过程中使用BigInteger
并不是一件坏事。 This way, you don't run the risk of overflow while multiplying these numbers. 这样,在将这些数字相乘时,您不会冒溢出的风险。
BigInteger bigAns = BigInteger.valueOf(number).multiply(BigInteger.valueOf(8))
.multiply(BigInteger.valueOf(1000000000L));
You are getting a negative number because you are exceeding the maximum possible value for a signed 32bit integer and causing an overflow. 您得到一个负数,因为您超出了有符号的32位整数的最大可能值,并导致溢出。
When dealing with large numbers like this, you should use long
instead, which is capable of holding much larger numbers. 当处理这样的大数时,应该改用long
,它可以容纳更大的数。
To implement this, change int ans = number * 8 * 1000000000
to long ans = number * 8 * 1000000000l
为此, int ans = number * 8 * 1000000000
更改为long ans = number * 8 * 1000000000l
The answer you get is a garbage value. 您得到的答案是垃圾值。 You can convert int to BigInteger by doing so: 您可以这样做,将int转换为BigInteger:
BigInteger bi = BigInteger.valueOf(myInteger.intValue());
And as Bohsulav said: 正如Bohsulav所说:
You can use this number * 8 * 1000000000l to prevent the overflow. 您可以使用此数字* 8 * 1000000000l来防止溢出。
Helped? 有帮助吗 Let me know :) 让我知道 :)
First convert to biginteger then perform the computations. 首先转换为biginteger, 然后执行计算。
BigInteger.valueOf(number * 8 * 1000000000);
Here, you perform the computation in int, then convert to BigInteger afterwards, when it is too late . 在这里,您以int进行计算,然后为时已晚 ,然后转换为BigInteger。
Use BigInteger.valueOf(number), then call appropriate methods to perform your computation. 使用BigInteger.valueOf(number),然后调用适当的方法来执行计算。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.