简体   繁体   中英

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). 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.

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));

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 to long ans = number * 8 * 1000000000l

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 :)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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