Reputation: 23
I'm trying to make a program that converts values to bits. Everything worked well till I got to GB(gigabytes). So for instance 1 GB should equal 8 billion bits but the result is giving me a negative answer. 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.
Upvotes: 1
Views: 1602
Reputation: 766
You are getting a negative number because you are exceeding the maximum possible value for a signed 32bit integer and causing an overflow.
When dealing with large numbers like this, you should use long
instead, which is capable of holding much larger numbers.
To implement this, change int ans = number * 8 * 1000000000
tolong ans = number * 8 * 1000000000l
Upvotes: 2
Reputation: 106400
It wouldn't be a bad thing to use BigInteger
throughout your calculations. 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));
Upvotes: 4
Reputation: 77454
First convert to biginteger then perform the computations.
BigInteger.valueOf(number * 8 * 1000000000);
Here, you perform the computation in int, then convert to BigInteger afterwards, when it is too late.
Use BigInteger.valueOf(number), then call appropriate methods to perform your computation.
Upvotes: 0
Reputation:
The answer you get is a garbage value. You can convert int to BigInteger by doing so:
BigInteger bi = BigInteger.valueOf(myInteger.intValue());
And as Bohsulav said:
You can use this number * 8 * 1000000000l to prevent the overflow.
Helped? Let me know :)
Upvotes: 0