How to convert numbers between hexadecimal and decimal

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

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

17条回答
  •  一生所求
    2020-11-22 05:55

    class HexToDecimal
    {
        static void Main()
        {
            while (true)
            {
                Console.Write("Enter digit number to convert: ");
                int n = int.Parse(Console.ReadLine()); // set hexadecimal digit number  
                Console.Write("Enter hexadecimal number: ");
                string str = Console.ReadLine();
                str.Reverse();
    
                char[] ch = str.ToCharArray();
                int[] intarray = new int[n];
    
                decimal decimalval = 0;
    
                for (int i = ch.Length - 1; i >= 0; i--)
                {
                    if (ch[i] == '0')
                        intarray[i] = 0;
                    if (ch[i] == '1')
                        intarray[i] = 1;
                    if (ch[i] == '2')
                        intarray[i] = 2;
                    if (ch[i] == '3')
                        intarray[i] = 3;
                    if (ch[i] == '4')
                        intarray[i] = 4;
                    if (ch[i] == '5')
                        intarray[i] = 5;
                    if (ch[i] == '6')
                        intarray[i] = 6;
                    if (ch[i] == '7')
                        intarray[i] = 7;
                    if (ch[i] == '8')
                        intarray[i] = 8;
                    if (ch[i] == '9')
                        intarray[i] = 9;
                    if (ch[i] == 'A')
                        intarray[i] = 10;
                    if (ch[i] == 'B')
                        intarray[i] = 11;
                    if (ch[i] == 'C')
                        intarray[i] = 12;
                    if (ch[i] == 'D')
                        intarray[i] = 13;
                    if (ch[i] == 'E')
                        intarray[i] = 14;
                    if (ch[i] == 'F')
                        intarray[i] = 15;
    
                    decimalval += intarray[i] * (decimal)Math.Pow(16, ch.Length - 1 - i);
    
                }
    
                Console.WriteLine(decimalval);
            }
    
        }
    
    }
    

提交回复
热议问题