Exemple #1
0
        public static object Power([NotNull] BigInteger x, [NotNull] BigInteger y)
        {
            int  yl;
            long y2;

            if (y.AsInt32(out yl))
            {
                return(Power(x, yl));
            }
            else if (y.AsInt64(out y2))
            {
                return(Power(x, y2));
            }
            else
            {
                if (x == BigInteger.Zero)
                {
                    if (y.Sign < 0)
                    {
                        throw PythonOps.ZeroDivisionError("0.0 cannot be raised to a negative power");
                    }
                    return(BigInteger.Zero);
                }
                else if (x == BigInteger.One)
                {
                    return(BigInteger.One);
                }
                else
                {
                    throw PythonOps.ValueError("Number too big");
                }
            }
        }
Exemple #2
0
        private static Expression BigIntegerConstant(BigInteger value)
        {
            int ival;

            if (value.AsInt32(out ival))
            {
                return(Expression.Call(
                           typeof(BigInteger).GetMethod("Create", new Type[] { typeof(int) }),
                           Expression.Constant(ival)
                           ));
            }

            long lval;

            if (value.AsInt64(out lval))
            {
                return(Expression.Call(
                           typeof(BigInteger).GetMethod("Create", new Type[] { typeof(long) }),
                           Expression.Constant(lval)
                           ));
            }

            return(Expression.New(
                       typeof(BigInteger).GetConstructor(new Type[] { typeof(int), typeof(uint[]) }),
                       Expression.Constant((int)value.Sign),
                       CreateUIntArray(value.GetBits())
                       ));
        }
Exemple #3
0
        public static object ParseInteger(string text, int b)
        {
            //!!! From experiments, CPython-1.3 appears to highly optimize this pattern
            //!!! Unfortunately, this has a small impact on parrotbench scores
            if (b == 0 && text.StartsWith("0x"))
            {
                int shift = 0;
                int ret   = 0;
                for (int i = text.Length - 1; i >= 2; i--)
                {
                    ret   |= HexValue(text[i]) << shift;
                    shift += 4;
                }
                return(ret);
            }

            if (b == 0)
            {
                b = DetectRadix(ref text);
            }
            try {
                return(ParseInt(text, b));
            } catch (OverflowException) {
                BigInteger ret = ParseBigInteger(text, b);
                int        iret;
                if (ret.AsInt32(out iret))
                {
                    return(iret);
                }
                return(ret);
            }
        }
        private static Expression BigIntegerConstant(BigInteger value)
        {
            int ival;

            if (value.AsInt32(out ival))
            {
                return(Expression.Call(
                           new Func <int, BigInteger>(BigInteger.Create).GetMethodInfo(),
                           Constant(ival)
                           ));
            }

            long lval;

            if (value.AsInt64(out lval))
            {
                return(Expression.Call(
                           new Func <long, BigInteger>(BigInteger.Create).GetMethodInfo(),
                           Constant(lval)
                           ));
            }

#if !FEATURE_NUMERICS
            return(Expression.Call(
                       new Func <int, uint[], BigInteger>(CompilerHelpers.CreateBigInteger).Method,
                       Constant((int)value.Sign),
                       CreateArray <uint>(value.GetWords())
                       ));
#else
            return(Expression.Call(
                       new Func <bool, byte[], BigInteger>(CompilerHelpers.CreateBigInteger).GetMethodInfo(),
                       Constant(value.Sign < 0),
                       CreateArray <byte>(value.Abs().ToByteArray())
                       ));
        }
Exemple #5
0
        private static Expression BigIntegerConstant(BigInteger value)
        {
            int ival;

            if (value.AsInt32(out ival))
            {
                return(Expression.Call(
                           new Func <int, BigInteger>(BigInteger.Create).GetMethodInfo(),
                           Constant(ival)
                           ));
            }

            long lval;

            if (value.AsInt64(out lval))
            {
                return(Expression.Call(
                           new Func <long, BigInteger>(BigInteger.Create).GetMethodInfo(),
                           Constant(lval)
                           ));
            }

            return(Expression.Call(
                       new Func <bool, byte[], BigInteger>(CompilerHelpers.CreateBigInteger).GetMethodInfo(),
                       Constant(value.Sign < 0),
                       CreateArray <byte>(value.Abs().ToByteArray())
                       ));
        }
Exemple #6
0
 public static char ToChar(BigInteger self, IFormatProvider provider) {
     int res;
     if (self.AsInt32(out res) && res <= Char.MaxValue && res >= Char.MinValue) {
         return (char)res;
     }
     throw new OverflowException("big integer won't fit into char");
 }
Exemple #7
0
        public static int Compare(BigInteger x, int y) {
            int ix;
            if (x.AsInt32(out ix)) {                
                return ix == y ? 0 : ix > y ? 1 : -1;
            }

            return BigInteger.Compare(x, y);
        }
Exemple #8
0
        public static object __int__(BigInteger x) {
            // The python spec says __int__  should return a long if needed, rather than overflow.
            int i32;
            if (x.AsInt32(out i32)) {
                return Microsoft.Scripting.Runtime.ScriptingRuntimeHelpers.Int32ToObject(i32);
            }

            return x;
        }
Exemple #9
0
        public static BigInteger Random(this Random generator, BigInteger limit)
        {
            ContractUtils.Requires(limit.Sign > 0, "limit");
            ContractUtils.RequiresNotNull(generator, "generator");

            BigInteger res = BigInteger.Zero;

            while (true)
            {
                // if we've run out of significant digits, we can return the total
                if (limit == BigInteger.Zero)
                {
                    return(res);
                }

                // if we're small enough to fit in an int, do so
                int iLimit;
                if (limit.AsInt32(out iLimit))
                {
                    return(res + generator.Next(iLimit));
                }

                // get the 3 or 4 uppermost bytes that fit into an int
                int    hiData;
                byte[] data  = limit.ToByteArray();
                int    index = data.Length;
                while (data[--index] == 0)
                {
                    ;
                }
                if (data[index] < 0x80)
                {
                    hiData        = data[index] << 24;
                    data[index--] = (byte)0;
                }
                else
                {
                    hiData = 0;
                }
                hiData       |= data[index] << 16;
                data[index--] = (byte)0;
                hiData       |= data[index] << 8;
                data[index--] = (byte)0;
                hiData       |= data[index];
                data[index--] = (byte)0;

                // get a uniform random number for the uppermost portion of the bigint
                byte[] randomData = new byte[index + 2];
                generator.NextBytes(randomData);
                randomData[index + 1] = (byte)0;
                res += new BigInteger(randomData);
                res += (BigInteger)generator.Next(hiData) << ((index + 1) * 8);

                // sum it with a uniform random number for the remainder of the bigint
                limit = new BigInteger(data);
            }
        }
Exemple #10
0
        /// <summary>
        /// Converts a BigInteger to int if it is small enough
        /// </summary>
        /// <param name="x">The value to convert</param>
        /// <returns>An int if x is small enough, otherwise x.</returns>
        /// <remarks>
        /// Use this helper to downgrade BigIntegers as necessary.
        /// </remarks>
        public static object Normalize(BigInteger x)
        {
            int result;

            if (x.AsInt32(out result))
            {
                return(ScriptingRuntimeHelpers.Int32ToObject(result));
            }
            return(x);
        }
Exemple #11
0
        internal static byte ToByteChecked(this BigInteger item)
        {
            int val;

            if (item.AsInt32(out val))
            {
                return(ToByteChecked(val));
            }
            throw PythonOps.ValueError("byte must be in range(0, 256)");
        }
Exemple #12
0
        public static int ConvertToInt32(BigInteger self)
        {
            int res;

            if (self.AsInt32(out res))
            {
                return(res);
            }

            throw Converter.CannotConvertOverflow("int", self);
        }
Exemple #13
0
        public object this[CodeContext /*!*/ context, BigInteger index] {
            get {
                int iVal;
                if (index.AsInt32(out iVal))
                {
                    return(this[context, iVal]);
                }

                throw PythonOps.IndexError("cannot fit long in index");
            }
        }
Exemple #14
0
        public static object EvalExpression(string code, Dictionary <string, object> localScope)
        {
            var scope = Prepare(localScope);

            try
            {
                ScriptSource source = scope.Engine.CreateScriptSourceFromString(code, SourceCodeKind.Expression);
                object       obj    = source.Execute(scope);

                if (obj != null && obj.GetType() == typeof(BigInteger))
                {
                    BigInteger bint = (BigInteger)obj;

                    int   i32;
                    uint  ui32;
                    long  i64;
                    ulong ui64;

                    if (bint.AsInt32(out i32))
                    {
                        return(i32);
                    }

                    if (bint.AsInt64(out i64))
                    {
                        return(i64);
                    }

                    if (bint.AsUInt32(out ui32))
                    {
                        return(ui32);
                    }

                    if (bint.AsUInt64(out ui64))
                    {
                        return(ui64);
                    }
                }

                return(obj);
            }
            catch (Exception ex)
            {
                throw new PeachException("Error executing expression [" + code + "]: " + ex.ToString(), ex);
            }
            finally
            {
                var names = scope.GetVariableNames().ToList();
                foreach (var name in names)
                {
                    scope.RemoveVariable(name);
                }
            }
        }
        public object this[BigInteger index] {
            get {
                int iVal;
                if (index.AsInt32(out iVal))
                {
                    return(this[iVal]);
                }

                throw PythonOps.IndexError("cannot fit long in index");
            }
            set {
                int iVal;
                if (index.AsInt32(out iVal))
                {
                    this[iVal] = value;
                    return;
                }

                throw PythonOps.IndexError("cannot fit long in index");
            }
        }
Exemple #16
0
        public static object /*!*/ BitwiseOr(int self, [NotNull] BigInteger /*!*/ other)
        {
            BigInteger result = other | self;
            int        ret;

            if (result.AsInt32(out ret))
            {
                return(ret);
            }
            else
            {
                return(result);
            }
        }
Exemple #17
0
        public int ToInt32()
        {
            int result;

            if (IsFixnum)
            {
                result = _fixnum;
            }
            else if (!_bignum.AsInt32(out result))
            {
                throw RubyExceptions.CreateRangeError("Bignum too big to convert into 32-bit signed integer");
            }
            return(result);
        }
Exemple #18
0
        private static object rangeWorker(BigInteger stop)
        {
            if (stop < BigInteger.Zero)
            {
                return(Range(0));
            }
            int istop;

            if (stop.AsInt32(out istop))
            {
                return(Range(istop));
            }
            throw Ops.OverflowError("too many items in the range");
        }
Exemple #19
0
        public static object ParseInteger(string text, int b)
        {
            Debug.Assert(b != 0);
            int iret;

            if (!ParseInt(text, b, out iret))
            {
                BigInteger ret = ParseBigInteger(text, b);
                if (!ret.AsInt32(out iret))
                {
                    return(ret);
                }
            }
            return(ScriptingRuntimeHelpers.Int32ToObject(iret));
        }
Exemple #20
0
        public static object ParseInteger(string text, int b)
        {
            Debug.Assert(b != 0);
            int iret;

            if (!ParseInt(text, b, out iret))
            {
                BigInteger ret = ParseBigInteger(text, b);
                if (!ret.AsInt32(out iret))
                {
                    return(ret);
                }
            }
            return(iret);
        }
Exemple #21
0
 public static object RightShift(BigInteger x, object other)
 {
     if (other is int)
     {
         return(RightShift(x, (int)other));
     }
     else if (other is BigInteger)
     {
         BigInteger y = (BigInteger)other;
         if (y < BigInteger.Zero)
         {
             throw Ops.ValueError("negative shift count");
         }
         int yint;
         if (y.AsInt32(out yint))
         {
             return(RightShift(x, yint));
         }
     }
     else if (other is long)
     {
         long y = (long)other;
         if (y < 0)
         {
             throw Ops.ValueError("negative shift count");
         }
         if (y <= Int32.MaxValue)
         {
             return(RightShift(x, (int)y));
         }
     }
     else if (other is bool)
     {
         return(RightShift(x, (bool)other ? 1 : 0));
     }
     else if (other is ExtensibleInt)
     {
         return(RightShift(x, ((ExtensibleInt)other).value));
     }
     else if (other is byte)
     {
         return(RightShift(x, (int)((byte)other)));
     }
     return(Ops.NotImplemented);
 }
Exemple #22
0
        private static object rangeWorker(BigInteger start, BigInteger stop)
        {
            if (start > stop)
            {
                stop = start;
            }
            BigInteger length = stop - start;
            int        ilength;

            if (length.AsInt32(out ilength))
            {
                List ret = List.MakeEmptyList(ilength);
                for (int i = 0; i < ilength; i++)
                {
                    ret.AddNoLock(start + i);
                }
                return(ret);
            }
            throw Ops.OverflowError("too many items in the range");
        }
Exemple #23
0
        public static int __hash__(BigInteger self)
        {
#if CLR4 // TODO: we might need our own hash code implementation. This avoids assertion failure.
            if (self == -2147483648)
            {
                return(-2147483648);
            }
#endif
            // Call the DLR's BigInteger hash function, which will return an int32 representation of
            // b if b is within the int32 range. We use that as an optimization for hashing, and
            // assert the assumption below.
            int hash = self.GetHashCode();
#if DEBUG
            int i;
            if (self.AsInt32(out i))
            {
                Debug.Assert(i == hash, String.Format("hash({0}) == {1}", i, hash));
            }
#endif
            return(hash);
        }
Exemple #24
0
        private static object LeftShift(BigInteger x, BigInteger y)
        {
            if (y < BigInteger.Zero)
            {
                throw Ops.ValueError("negative shift count");
            }
            int yint;

            if (y.AsInt32(out yint))
            {
                return(x << yint);
            }
            if (x == BigInteger.Zero)
            {
                return(BigInteger.Zero);
            }
            else
            {
                throw Ops.OverflowError("number too big");
            }
        }
Exemple #25
0
        public static int __hash__(BigInteger self)
        {
            // TODO: we might need our own hash code implementation. This avoids assertion failure.
            if (self == -2147483648)
            {
                return(-2147483648);
            }

            // check if it's in the Int64 or UInt64 range, and use the built-in hashcode for that instead
            // this ensures that objects added to dictionaries as (U)Int64 can be looked up with Python longs
            Int64 i64;

            if (self.AsInt64(out i64))
            {
                return(Int64Ops.__hash__(i64));
            }
            else
            {
                UInt64 u64;
                if (self.AsUInt64(out u64))
                {
                    return(UInt64Ops.__hash__(u64));
                }
            }

            // Call the DLR's BigInteger hash function, which will return an int32 representation of
            // b if b is within the int32 range. We use that as an optimization for hashing, and
            // assert the assumption below.
            int hash = self.GetHashCode();

#if DEBUG
            int i;
            if (self.AsInt32(out i))
            {
                Debug.Assert(i == hash, String.Format("hash({0}) == {1}", i, hash));
            }
#endif
            return(hash);
        }
Exemple #26
0
 public static object LeftShift(long x, object other)
 {
     if (other is int)
     {
         return(LeftShift(x, (int)other));
     }
     else if (other is long)
     {
         long y = (long)other;
         if (Int32.MinValue <= y && y <= Int32.MaxValue)
         {
             return(LeftShift(x, (int)y));
         }
     }
     else if (other is bool)
     {
         return(LeftShift(x, (bool)other ? 1 : 0));
     }
     else if (other is BigInteger)
     {
         BigInteger big = (BigInteger)other;
         int        y;
         if (big.AsInt32(out y))
         {
             return(LeftShift(x, y));
         }
     }
     else if (other is ExtensibleInt)
     {
         return(LeftShift(x, ((ExtensibleInt)other).value));
     }
     else if (other is byte)
     {
         return(LeftShift(x, (int)((byte)other)));
     }
     return(Ops.NotImplemented);
 }
Exemple #27
0
 public static bool AsInt32(BigInteger self, out int res)
 {
     return(self.AsInt32(out res));
 }
Exemple #28
0
        public static string /*!*/ __format__(CodeContext /*!*/ context, BigInteger /*!*/ self, [NotNull] string /*!*/ formatSpec)
        {
            StringFormatSpec spec = StringFormatSpec.FromString(formatSpec);

            if (spec.Precision != null)
            {
                throw PythonOps.ValueError("Precision not allowed in integer format specifier");
            }

            BigInteger val = self;

            if (self < 0)
            {
                val = -self;
            }
            string digits;

            switch (spec.Type)
            {
            case 'n':
                CultureInfo culture = context.LanguageContext.NumericCulture;

                if (culture == CultureInfo.InvariantCulture)
                {
                    // invariant culture maps to CPython's C culture, which doesn't
                    // include any formatting info.
                    goto case 'd';
                }

                digits = FormattingHelper.ToCultureString(val, context.LanguageContext.NumericCulture.NumberFormat, spec);
                break;

            case null:
            case 'd':
                if (spec.ThousandsComma)
                {
                    var width = spec.Width ?? 0;
                    // If we're inserting commas, and we're padding with leading zeros.
                    // AlignNumericText won't know where to place the commas,
                    // so force .Net to help us out here.
                    if (spec.Fill.HasValue && spec.Fill.Value == '0' && width > 1)
                    {
                        digits = val.ToString(FormattingHelper.ToCultureString(self, FormattingHelper.InvariantCommaNumberInfo, spec));
                    }
                    else
                    {
                        digits = val.ToString("#,0", CultureInfo.InvariantCulture);
                    }
                }
                else
                {
                    digits = val.ToString("D", CultureInfo.InvariantCulture);
                }
                break;

            case '%':
                if (spec.ThousandsComma)
                {
                    digits = val.ToString("#,0.000000%", CultureInfo.InvariantCulture);
                }
                else
                {
                    digits = val.ToString("0.000000%", CultureInfo.InvariantCulture);
                }
                break;

            case 'e':
                if (spec.ThousandsComma)
                {
                    digits = val.ToString("#,0.000000e+00", CultureInfo.InvariantCulture);
                }
                else
                {
                    digits = val.ToString("0.000000e+00", CultureInfo.InvariantCulture);
                }
                break;

            case 'E':
                if (spec.ThousandsComma)
                {
                    digits = val.ToString("#,0.000000E+00", CultureInfo.InvariantCulture);
                }
                else
                {
                    digits = val.ToString("0.000000E+00", CultureInfo.InvariantCulture);
                }
                break;

            case 'f':
            case 'F':
                if (spec.ThousandsComma)
                {
                    digits = val.ToString("#,########0.000000", CultureInfo.InvariantCulture);
                }
                else
                {
                    digits = val.ToString("#########0.000000", CultureInfo.InvariantCulture);
                }
                break;

            case 'g':
                if (val >= 1000000)
                {
                    digits = val.ToString("0.#####e+00", CultureInfo.InvariantCulture);
                }
                else if (spec.ThousandsComma)
                {
                    goto case 'd';
                }
                else
                {
                    digits = val.ToString(CultureInfo.InvariantCulture);
                }
                break;

            case 'G':
                if (val >= 1000000)
                {
                    digits = val.ToString("0.#####E+00", CultureInfo.InvariantCulture);
                }
                else if (spec.ThousandsComma)
                {
                    goto case 'd';
                }
                else
                {
                    digits = val.ToString(CultureInfo.InvariantCulture);
                }
                break;

            case 'X':
                digits = AbsToHex(val, false);
                break;

            case 'x':
                digits = AbsToHex(val, true);
                break;

            case 'o':     // octal
                digits = ToOctal(val, true);
                break;

            case 'b':     // binary
                digits = ToBinary(val, false, true);
                break;

            case 'c':     // single char
                int iVal;
                if (spec.Sign != null)
                {
                    throw PythonOps.ValueError("Sign not allowed with integer format specifier 'c'");
                }
                else if (!self.AsInt32(out iVal))
                {
                    throw PythonOps.OverflowError("long int too large to convert to int");
                }
                else if (iVal < 0 || iVal > 0xFF)
                {
                    throw PythonOps.OverflowError("%c arg not in range(0x10000)");
                }

                digits = ScriptingRuntimeHelpers.CharToString((char)iVal);
                break;

            default:
                throw PythonOps.ValueError("Unknown format code '{0}'", spec.Type.ToString());
            }

            Debug.Assert(digits[0] != '-');

            return(spec.AlignNumericText(digits, self.IsZero(), self.IsPositive()));
        }
Exemple #29
0
 public static Variable MakeInt(BigInteger v)
 {
     int vs;
     if (v.AsInt32(out vs)) return Kernel.BoxAnyMO<int>(vs, Kernel.IntMO);
     else return Kernel.BoxAnyMO<BigInteger>(v, Kernel.IntMO);
 }
Exemple #30
0
        public static string /*!*/ __format__(CodeContext /*!*/ context, BigInteger /*!*/ self, [NotNull] string /*!*/ formatSpec)
        {
            StringFormatSpec spec = StringFormatSpec.FromString(formatSpec);

            if (spec.Precision != null)
            {
                throw PythonOps.ValueError("Precision not allowed in integer format specifier");
            }

            BigInteger val = self;

            if (self < 0)
            {
                val = -self;
            }
            string digits;

            switch (spec.Type)
            {
            case 'n':
                CultureInfo culture = PythonContext.GetContext(context).NumericCulture;

                if (culture == CultureInfo.InvariantCulture)
                {
                    // invariant culture maps to CPython's C culture, which doesn't
                    // include any formatting info.
                    goto case 'd';
                }

                digits = ToCultureString(val, PythonContext.GetContext(context).NumericCulture);
                break;

#if CLR2
            case null:
            case 'd':
                digits = val.ToString();
                break;

            case '%':
                if (val == BigInteger.Zero)
                {
                    digits = "0.000000%";
                }
                else
                {
                    digits = val.ToString() + "00.000000%";
                }
                break;

            case 'e': digits = ToExponent(val, true, 6, 7); break;

            case 'E': digits = ToExponent(val, false, 6, 7); break;

            case 'f':
                if (val != BigInteger.Zero)
                {
                    digits = val.ToString() + ".000000";
                }
                else
                {
                    digits = "0.000000";
                }
                break;

            case 'F':
                if (val != BigInteger.Zero)
                {
                    digits = val.ToString() + ".000000";
                }
                else
                {
                    digits = "0.000000";
                }
                break;

            case 'g':
                if (val >= 1000000)
                {
                    digits = ToExponent(val, true, 0, 6);
                }
                else
                {
                    digits = val.ToString();
                }
                break;

            case 'G':
                if (val >= 1000000)
                {
                    digits = ToExponent(val, false, 0, 6);
                }
                else
                {
                    digits = val.ToString();
                }
                break;
#else
            case null:
            case 'd':
                if (spec.ThousandsComma)
                {
                    digits = val.ToString("#,0", CultureInfo.InvariantCulture);
                }
                else
                {
                    digits = val.ToString("D", CultureInfo.InvariantCulture);
                }
                break;

            case '%':
                if (spec.ThousandsComma)
                {
                    digits = val.ToString("#,0.000000%", CultureInfo.InvariantCulture);
                }
                else
                {
                    digits = val.ToString("0.000000%", CultureInfo.InvariantCulture);
                }
                break;

            case 'e':
                if (spec.ThousandsComma)
                {
                    digits = val.ToString("#,0.000000e+00", CultureInfo.InvariantCulture);
                }
                else
                {
                    digits = val.ToString("0.000000e+00", CultureInfo.InvariantCulture);
                }
                break;

            case 'E':
                if (spec.ThousandsComma)
                {
                    digits = val.ToString("#,0.000000E+00", CultureInfo.InvariantCulture);
                }
                else
                {
                    digits = val.ToString("0.000000E+00", CultureInfo.InvariantCulture);
                }
                break;

            case 'f':
            case 'F':
                if (spec.ThousandsComma)
                {
                    digits = val.ToString("#,########0.000000", CultureInfo.InvariantCulture);
                }
                else
                {
                    digits = val.ToString("#########0.000000", CultureInfo.InvariantCulture);
                }
                break;

            case 'g':
                if (val >= 1000000)
                {
                    digits = val.ToString("0.#####e+00", CultureInfo.InvariantCulture);
                }
                else if (spec.ThousandsComma)
                {
                    digits = val.ToString("#,0", CultureInfo.InvariantCulture);
                }
                else
                {
                    digits = val.ToString(CultureInfo.InvariantCulture);
                }
                break;

            case 'G':
                if (val >= 1000000)
                {
                    digits = val.ToString("0.#####E+00", CultureInfo.InvariantCulture);
                }
                else if (spec.ThousandsComma)
                {
                    digits = val.ToString("#,0", CultureInfo.InvariantCulture);
                }
                else
                {
                    digits = val.ToString(CultureInfo.InvariantCulture);
                }
                break;
#endif
            case 'X':
                digits = AbsToHex(val, false);
                break;

            case 'x':
                digits = AbsToHex(val, true);
                break;

            case 'o':     // octal
                digits = ToOctal(val, true);
                break;

            case 'b':     // binary
                digits = ToBinary(val, false, true);
                break;

            case 'c':     // single char
                int iVal;
                if (spec.Sign != null)
                {
                    throw PythonOps.ValueError("Sign not allowed with integer format specifier 'c'");
                }
                else if (!self.AsInt32(out iVal))
                {
                    throw PythonOps.OverflowError("long int too large to convert to int");
                }
                else if (iVal < 0 || iVal > 0xFF)
                {
                    throw PythonOps.OverflowError("%c arg not in range(0x10000)");
                }

                digits = ScriptingRuntimeHelpers.CharToString((char)iVal);
                break;

            default:
                throw PythonOps.ValueError("Unknown format code '{0}'", spec.Type.ToString());
            }

            Debug.Assert(digits[0] != '-');

            return(spec.AlignNumericText(digits, self.IsZero(), self.IsPositive()));
        }
 private void AsInt32Test(BigInteger i, bool expRet, int expInt)
 {
     int v;
     bool b = i.AsInt32(out v);
     Expect(b, EqualTo(expRet));
     Expect(v, EqualTo(expInt));
 }
Exemple #32
0
        public static object Compare(BigInteger x, object y)
        {
            if (y == null)
            {
                return(1);
            }

            int intVal;

            if (y is int)
            {
                if (x.AsInt32(out intVal))
                {
                    return(IntOps.Compare(intVal, y));
                }
            }
            else if (y is ExtensibleInt)
            {
                if (x.AsInt32(out intVal))
                {
                    return(IntOps.Compare(intVal, ((ExtensibleInt)y).value));
                }
            }
            else if (y is double)
            {
                double dbl = x.ToFloat64();
                return(FloatOps.Compare(dbl, y));
            }
            else if (y is ExtensibleFloat)
            {
                double dbl = x.ToFloat64();
                return(FloatOps.Compare(dbl, ((ExtensibleFloat)y).value));
            }
            else if (y is bool)
            {
                if (x.AsInt32(out intVal))
                {
                    return(IntOps.Compare(intVal, ((bool)y) ? 1 : 0));
                }
            }
            else if (y is decimal)
            {
                double dbl = x.ToFloat64();
                return(FloatOps.Compare(dbl, y));
            }

            Conversion conv;
            BigInteger bi = Converter.TryConvertToBigInteger(y, out conv);

            if (conv == Conversion.None)
            {
                object res = Ops.GetDynamicType(y).Coerce(y, x);
                if (res != Ops.NotImplemented && !(res is OldInstance))
                {
                    return(Ops.Compare(((Tuple)res)[1], ((Tuple)res)[0]));
                }
                return(Ops.NotImplemented);
            }

            BigInteger diff = x - bi;

            if (diff == 0)
            {
                return(0);
            }
            else if (diff < 0)
            {
                return(-1);
            }
            else
            {
                return(1);
            }
        }
Exemple #33
0
        public static object reduce(BigInteger val)
        {
            //int bitLength = val.bitLength();
            //return (bitLength < 32)
            //    ? (object)val.intValue()
            //    : (bitLength < 64)
            //        ? (object)val.longValue()
            //        : val;
            int ival;
            if (val.AsInt32(out ival))
                return ival;

            long lval;
            if (val.AsInt64(out lval))
                return lval;

            return val;
        }