C# 進制轉換

/// <summary>
        /// 十進制數轉換成二、八、十六進制數
        /// </summary>
        /// <param name="int_value">十進制數</param>
        /// <param name="mod">進制</param>
        /// <returns></returns>
        public static string IntToHex(int int_value, int mod)
        {
            string hex_value = string.Empty;
            int add_value, mod_value, temp;
            char char_mod_value;
            temp = int_value;
            while (temp > 0)
            {
                add_value = temp / mod;
                mod_value = temp % mod;
                if (mod_value >= 10)
                {
                    char_mod_value = (char)(mod_value + 55);
                }
                else
                {
                    char_mod_value = (char)(mod_value + 48);
                }
                hex_value = char_mod_value + hex_value;
                temp = add_value;
            }
            return hex_value; ;
        }


 

 /// <summary>
        /// 非十進制數轉換成十進制
        /// </summary>
        /// <param name="hex_value">非十進制數</param>
        /// <param name="mod">模</param>
        /// <returns>十進制數</returns>
        public static int HexToInt(string hex_value, int mod)
        {
            int value = 0;
            for (int i = 0; i < hex_value.Length; i++)
            {
                int asc = Convert.ToInt32(hex_value[i]);
                if (asc >= 65)
                {
                    value = value + Convert.ToInt32((asc - 55) * System.Math.Pow(Convert.ToDouble(mod), Convert.ToDouble(hex_value.Length - i - 1)));
                }
                else
                {
                    value = value + Convert.ToInt32((asc - 48) * System.Math.Pow(Convert.ToDouble(mod), Convert.ToDouble(hex_value.Length - i - 1)));
                }
            }
            return value;
        }


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章