Exemple #1
0
        public static uint ToUInt32(string value, int fromBase)
        {
            // 使用内置方法,会快一些。
            if (fromBase == 2 || fromBase == 8 || fromBase == 10 || fromBase == 16)
            {
                return(Convert.ToUInt32(value, fromBase));
            }
            // 使用自己的算法。
            if (value == null)
            {
                return(0U);
            }
            CheckBaseConvert(value, fromBase);
            uint result = 0;
            uint uBase  = (uint)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();
                    }
                }
                uint next = unchecked (result * uBase + (uint)t);
                // 判断是否超出 UInt32 的范围。
                if (next < result)
                {
                    throw ExceptionHelper.OverflowUInt32();
                }
                result = next;
            }
            return(result);
        }