十进制转十六进制

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConvertDecimalToHex
{
    /// <summary>
    /// 十进制转十六进制
    /// </summary>
    class Program
    {
        static void Main(string[] args)
        {
            int dec = 2520;
            Console.WriteLine("The Hex of Decimal [{0}] is: [{1}]", dec, Convert(dec));
            Console.ReadKey();
        }

        private static string Convert(int input)
        {
            if (input < 16) return OutputHex(input);

            int temp;
            string sb = "";

            while (input >= 16)
            {
                temp = input;
                sb += (OutputHex(temp % 16)); // 把余数添加到临时数组中
                input = input / 16;
            }

            sb += OutputHex(input).ToString();  // 保存退出循环时input的值
            
            string tempStr = "";
            
            // 将余数反序输出
            for (int i = sb.Length - 1; i >= 0; i--)
            {
                tempStr += sb[i].ToString();
            }

            return tempStr;
        }

        public static string OutputHex(int hex)
        {
            string output;

            switch (hex)
            {
                case 10: output = "A"; break;
                case 11: output = "B"; break;
                case 12: output = "C"; break;
                case 13: output = "D"; break;
                case 14: output = "E"; break;
                case 15: output = "F"; break;
                default: output = hex.ToString(); break;
            }

            return output;
        }
    }
}

你可能感兴趣的:(十进制转十六进制)