/// <summary> /// Converts BigInteger to the minimal possible number type /// Negative numbers get converted to positive numbers prefixed with '-' /// For example, -520582(BigInteger) -> '-'(char) 52082(int) /// </summary> object[] ConvertBigIntegerToRefalNumber(BigInteger bigIntValue) { var negative = bigIntValue < 0; var result = new object[negative ? 2 : 1]; var valueIndex = negative ? 1 : 0; if (negative) { result[0] = '-'; bigIntValue = -bigIntValue; } int intValue; long longValue; if (bigIntValue.AsInt32(out intValue)) { result[valueIndex] = intValue; } else if (bigIntValue.AsInt64(out longValue)) { result[valueIndex] = longValue; } else { result[valueIndex] = bigIntValue; } return(result); }
// extract arguments and convert to BigIntegers void GetBigIntegerArguments(PassiveExpression expr, out BigInteger arg1, out BigInteger arg2) { object op1, op2; GetArguments(expr, out op1, out op2); arg1 = ToBigInteger(op1); arg2 = ToBigInteger(op2);; }
// find the first numeric symbol in an expression and convert to BigInteger BigInteger ToBigInteger(object value) { // try convert expression var expr = value as PassiveExpression; if (expr != null) { int sign = 1; foreach (object o in expr) { if (o is StructureBrace) { continue; } if (o is char) { var c = (char)o; if (c == '-') { sign *= -1; } } if (o is int) { return(BigInteger.Create(sign * (int)o)); } if (o is long) { return(BigInteger.Create(sign * (long)o)); } if (o is BigInteger) { return(sign * (BigInteger)o); } // warning: BigInteger doesn't support parsing strings if (o is string) { return(BigInteger.Create(sign * Convert.ToInt64(o))); } } return(BigInteger.Zero); } // try convert single symbol if (value is int) { return(BigInteger.Create((int)value)); } if (value is long) { return(BigInteger.Create((long)value)); } if (value is BigInteger) { return((BigInteger)value); } if (value is string) { return(BigInteger.Create(Convert.ToInt64(value))); } return(BigInteger.Zero); }