Exemple #1
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);
        }