进制转换

核心代码

        /// <summary>
        /// 
        /// </summary>
        /// <param name="num">要转换的数</param>
        /// <param name="jz1">输入数的进制</param>
        /// <param name="jz2">要转换的进制</param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult Index(string num, int jz1, int jz2)
        {
            try
            {
                int aaa = xtod(num.ToCharArray(), jz1); //先转为十进制
                string str = dtox(aaa, jz2); //再把十进制转为目标进制
                str = "结果是:" + str;
                return Content(str);
            }
            catch (Exception ex)
            {

               return Content("出错:"+ex.Message);
            }

        }

        /// <summary>
        /// 整数幂运算函数
        /// </summary>
        /// <param name="x">底数</param>
        /// <param name="y">指数</param>
        /// <returns></returns>
        int int_pow(int x, int y) {
            int i, result = 1;
            for (i = 1; i <= y; i++) {
                result *= x;
            }
            return result;
        }
        /// <summary>
        /// 将十进制数转为任意进制
        /// </summary>
        /// <param name="dnum">十进制数</param>
        /// <param name="jz">目标进制</param>
        string dtox(int dnum, int jz) {
            char[] xnum = new char[100] ; //保存目标进制的各位数,从右向左数,如:下标0是右边第1位,下标1是右边往左数第2位
            int i = 0, j = 0;  
            while (dnum >=jz)//用除模取余法计算对应进制的各位
            {
                if (dnum % jz <= 9)
                {
                    xnum[j++] = (char)(dnum % jz + 48); //0~9之间的数
                }
                else
                {
                    xnum[j++] =(char) (dnum % jz - 10 + 'A'); //超过9的数字用大写字母表示
                }
                dnum = dnum / jz;
            }
            if (dnum<=9)
            {
                xnum[j] =(char) (dnum + '0');
            }
            else
            {
                xnum[j] = (char)(dnum - 10 + 'A');
            }
           string aaa = "";
            for ( i = j; i >= 0; i--)
            {
                aaa += xnum[i];
            }
            return aaa;
        }
        /// <summary>
        /// 转为十进制
        /// </summary>
        /// <param name="num">输入的字符串</param>
        /// <param name="jz">源数据的进制</param>
        /// <returns></returns>
        int xtod(char[] num, int jz) {
            int dnum = 0, i = 0, n = 0, b = 0; 
            n = num.Length;
            for (i=n-1;i>=0 ; i--)
            {
                if (num[n - i - 1] >= 'a')
                    b = num[n - i - 1] - 'a' + 10; //小写字母
                else if (num[n - i - 1] >= 'A')
                    b = num[n - i - 1] - 'A' + 10; //大写字母
                else
                    b = num[n - i - 1] - '0';
                dnum = dnum + b * int_pow(jz, i);
            }
            return dnum;
        }