C#十进制与任意进制的转换

/// <summary>
        /// 将十进制转换为指定的进制
        /// </summary>
        /// <param name="Val">十进制值</param>
        /// <param name="TargetRadix">目标进制</param>
        /// <param name="BaseChar">基数列表(长度必须大于源字符串进制,无I,O)</param>
        /// <returns></returns>
        public static string JinZhiConvert(ulong Val, int TargetRadix = 0, string BaseChar = "0123456789ABCDEFGHJKLMNPQRSTUVWXYZ")
        {
            if (TargetRadix == 0 && BaseChar.Length == 0) return "长度与基数不能同时为零";
            if (TargetRadix <= 0) TargetRadix = BaseChar.Length;
            List<string> r = new List<string>();
            do
            {
                ulong y = Val % (ulong)TargetRadix;
                r.Add(BaseChar[Convert.ToInt32(y)].ToString());
                Val = Convert.ToUInt64(Math.Floor(Val / (decimal)TargetRadix));
            } while (Val > 0);
            r.Reverse();
            return string.Join("", r.ToArray());
        }


        /// <summary>
        /// 将任意进制转化为十制
        /// </summary>
        /// <param name="Val">任意进制的字任串</param>
        /// <param name="SourceRadix">源字符串的进制</param>
        /// <param name="BaseChar">基数列表(长度必须大于源字符串进制,无I,O)</param>
        /// <returns></returns>
        public static ulong JinZhiConvert(string Val, int SourceRadix = 0, string BaseChar = "0123456789ABCDEFGHJKLMNPQRSTUVWXYZ")
        {
            ulong r = 0;
            if (BaseChar == "") return 0;
            if (SourceRadix == 0) SourceRadix = BaseChar.Length;
            List<char> v = Val.ToCharArray().ToList();
            v.Reverse();
            for (int i = 0; i < v.Count; i++)
            {
                int index = BaseChar.IndexOf(v[i]);
                if (index > -1)
                    r += Convert.ToUInt64(index * Math.Pow(SourceRadix, i));
            }
            return r;
        }

  

posted @ 2023-06-19 15:18  China Soft  阅读(48)  评论(0编辑  收藏  举报