示例#1
0
 /// <summary>
 /// 对给定的基数和字符串进行检查。
 /// </summary>
 /// <param name="value">包含要转换的数字的字符串,
 /// 使用不区分大小写的字母表示大于 <c>10</c> 的数。</param>
 /// <param name="fromBase"><paramref name="value"/> 中数字的基数,
 /// 它必须位于 <c>2</c> 到 <c>36</c> 之间。</param>
 /// <exception cref="System.ArgumentOutOfRangeException">
 /// <paramref name="fromBase"/> 不是 <c>2</c> 到 <c>36</c> 之间的数字。</exception>
 /// <exception cref="System.FormatException">
 /// <paramref name="value"/> 表示一个非 <c>10</c> 为基的有符号数,
 /// 但前面带一个负号。</exception>
 private static void CheckBaseConvert(string value, int fromBase)
 {
     // 基数检查。
     if (fromBase < 3 || fromBase > 36)
     {
         throw ExceptionHelper.InvalidBase("toBase");
     }
     if (value.Length == 0)
     {
         throw ExceptionHelper.NoParsibleDigits();
     }
     // 负号检查。
     if (value[0] == '-')
     {
         throw ExceptionHelper.BaseConvertNegativeValue();
     }
 }
示例#2
0
        public static ulong ToUInt64(string value, int fromBase)
        {
            // 使用内置方法,会快一些。
            if (fromBase == 2 || fromBase == 8 || fromBase == 10 || fromBase == 16)
            {
                return(Convert.ToUInt64(value, fromBase));
            }
            // 使用自己的算法。
            if (value == null)
            {
                return(0UL);
            }
            CheckBaseConvert(value, fromBase);
            ulong result = 0;
            ulong ulBase = (ulong)fromBase;

            for (int i = 0; i < value.Length; i++)
            {
                int t = GetBaseValue(value[i], fromBase);
                if (t < 0)
                {
                    if (i == 0)
                    {
                        throw ExceptionHelper.NoParsibleDigits();
                    }
                    else
                    {
                        throw ExceptionHelper.ExtraJunkAtEnd();
                    }
                }
                ulong next = unchecked (result * ulBase + (ulong)t);
                // 判断是否超出 UInt64 的范围。
                if (next < result)
                {
                    throw ExceptionHelper.OverflowUInt64();
                }
                result = next;
            }
            return(result);
        }