How to convert numbers between hexadecimal and decimal

前端 未结 17 1101
情歌与酒
情歌与酒 2020-11-22 05:30

How do you convert between hexadecimal numbers and decimal numbers in C#?

17条回答
  •  别那么骄傲
    2020-11-22 06:05

    My solution is a bit like back to basics, but it works without using any built-in functions to convert between number systems.

        public static string DecToHex(long a)
        {
            int n = 1;
            long b = a;
            while (b > 15)
            {
                b /= 16;
                n++;
            }
            string[] t = new string[n];
            int i = 0, j = n - 1;
            do
            {
                     if (a % 16 == 10) t[i] = "A";
                else if (a % 16 == 11) t[i] = "B";
                else if (a % 16 == 12) t[i] = "C";
                else if (a % 16 == 13) t[i] = "D";
                else if (a % 16 == 14) t[i] = "E";
                else if (a % 16 == 15) t[i] = "F";
                else t[i] = (a % 16).ToString();
                a /= 16;
                i++;
            }
            while ((a * 16) > 15);
            string[] r = new string[n];
            for (i = 0; i < n; i++)
            {
                r[i] = t[j];
                j--;
            }
            string res = string.Concat(r);
            return res;
        }
    

提交回复
热议问题