转换整形数字为16进制字符串

例如15则返回F,20则返回14.

 

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

namespace ConsoleApplication20
{
    class Program
    {
        static void Main(string[] args)
        {
            int n = -18;
            Console.Write(ConvertIntToHex(n));
        }

        static string ConvertIntToHex(int n)
        {
            if (n == 0)
            {
                return "0";
            }
            StringBuilder sb = new StringBuilder();
            char sign = ' ';
            int a = n;
            int b = 0;
            if (n<0)
            {
                sign = '-';
                a = a * -1;
            }
            while (a>0)
            {
                b = a % 16;
                sb.Insert(0,(GetHexValue(b)));
                a = a / 16;
            }
            if (n<0)
            {
                sb.Insert(0, sign);
            }
            

            return sb.ToString();
        }

        static char GetHexValue(int n)
        {
            if (n<0||n>15)
            {
                throw new Exception("input must greater than or equal 0, also less than 16");
            }
            char chr = ' ';
            if (n<10)
            {
                chr = (char)(n+48);
                return chr;
            }
            else
            {
                return (char)(n - 10 + 'A');
            }
        }
    }
}
View Code

 

posted @ 2014-02-18 16:15  Ligeance  阅读(993)  评论(0编辑  收藏  举报