I have this code:
public BigInteger getNum()
{
BigInteger rtrnVal = 0;
for (int a = _arr.Count; a > 0; a--)
{
rtrnVal = rtrnVal + (_arr[a] ? BigInteger.Pow(2, a) : 0);
}
return rtrnVal;
}
_arr is a List<bool>. In the specific testing circumstances, _arr is:
1001011100001010001100101111010010101100010011000101100000101100010111101001001101010100001001000001100001010010000011001110
with 1 being true and 0 being false respectively.
It should return 12547898989848949849191494989874798798.
Why am I getting this overflow exception?
To be exact: I get the error on this line:
rtrnVal = rtrnVal + (_arr[a] ? BigInteger.Pow(2, a) : 0);
Edit: Here is the code that calls it:
Stopwatch st = new Stopwatch();
BigInteger x = 0;
numToBin a = new numToBin();
st.Start();
for(x = 0; x< 1000; x++)
{
a = new numToBin(x);
bool[] b = a.getBits();
}
long t1 = st.ElapsedMilliseconds;
st.Restart();
a = new numToBin(BigInteger.Parse("12547898989848949849191494989874798798"));
bool[] y = a.getBits();
foreach(bool z in y)
{
Console.Write(z ? "1" : "0");
}
Console.WriteLine();
long t2 = st.ElapsedMilliseconds;
st.Restart();
a = new numToBin(y);
Console.WriteLine(a.getNum());
long t3 = st.ElapsedMilliseconds;
And so this leads me to think that the error is in the constructor:
public numToBin(BigInteger n)
{
_arr = new List<bool>();
int remainder;
while (n != 0)
{
remainder = (int)(n % 2);
n = n / 2;
_arr.Add(remainder == 1 ? true : false);
}
}
But even there I think that the code is ok...
Edit2: Here is the stack trace:
System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
at System.ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument
argument, ExceptionResource resource)
at System.Collections.Generic.List`1.get_Item(Int32 index)
at Testing_app.Program.numToBin.getNum() in
C:\Users\MYNAME\Source\Repos\First project\Testing app\Program.cs:line 108
rtrnVal = rtrnVal + (_arr[a] ? BigInteger.Pow(2, a) : 0);is doing the wrong thing. In the first iteration of your loop a = 124 giving you the last digit but you are then adding2^ato your running total rather than just 1.