1

I am writing an object interface of type BigInteger that accepts ints as parameters. This has worked well so far with one exception which worries me. Is it safe to convert from BigInteger down to int? I know that it is alright to go in the opposite direction, but it seems like there could arise serious problems if the BigInt I am trying to down-convert is larger than int's range. I need to build some functionality into my interface to allow this, however. What is wise here? How should I proceed?

Mr_Dave
  • 547
  • 1
  • 8
  • 17
  • How would accepting ints as a parameter to create a biginteger mean you're converting bigintegers to ints? – Sam Hanley Oct 31 '14 at 01:17
  • The method in question performs addition between two BigInteger objects. It returns a newly constructed object, BigInteger BigInt(int numerator, int common_denominator). I am having problems getting things back into terms of (int, int) to finally call the constructor. I apologize if this formatting of mine is all messed up, btw. This is literally the first question I have posted on this site. – Mr_Dave Oct 31 '14 at 01:26

1 Answers1

2

It is definitely not safe to convert a BigInteger to an int, as you would be vulnerable to overflow.

In order to get around this, you would have to put in a condition, that makes sure that you will not convert BigIntegers outside the ints range, which is:

Integer.MAX_VALUE =  2147483647
Integer.MIN_VALUE = -2147483648

You could consider if long is sufficient for you use though. It has significantly wider bounds:

Long.MAX_VALUE =  9223372036854775807
Long.MIN_VALUE = -9223372036854775808
Community
  • 1
  • 1
habitats
  • 2,203
  • 2
  • 23
  • 31