Simooo

Hex to Decimal

Jun 21st, 2015
272
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.61 KB | None | 0 0
  1. using System;
  2.  
  3. class HexademicalToDecimal
  4. {
  5.     static void Main()
  6.     {
  7.         string hex = Console.ReadLine();      
  8.         long resultindecimal = 0;
  9.         int element = 0;
  10.  
  11.         for (int i = hex.Length - 1; i >= 0; i--)
  12.         {
  13.             if (hex[i] == 'A' ||hex[i] == 'B' || hex[i] == 'C' || hex[i] == 'D' || hex[i] == 'E'|| hex[i] == 'F')
  14.             {
  15.                 element = int.Parse(HexLettersToDecimal(hex[i]));
  16.             }
  17.             else
  18.             {
  19.                 element = hex[i] - '0';
  20.             }            
  21.  
  22.             resultindecimal += element * PowerOf(hex.Length - (i + 1));
  23.  
  24.         }
  25.         Console.WriteLine(resultindecimal);
  26.        
  27.  
  28.     }
  29.     static long PowerOf(int grade)
  30.     {
  31.         long result = 1;
  32.         int poweredNum = 16;
  33.         for (int i = 1; i <= grade; i++)
  34.         {
  35.  
  36.             result *= poweredNum;
  37.         }
  38.  
  39.         return result;
  40.     }
  41.  
  42.     static string HexLettersToDecimal(char hex)
  43.     {
  44.         string element = "";
  45.         if (hex == 'A')
  46.         {
  47.            element = "10";
  48.            
  49.         }
  50.         else if (hex == 'B')
  51.         {
  52.             element = "11";
  53.            
  54.         }
  55.         else if (hex == 'C')
  56.         {
  57.             element = "12";
  58.            
  59.         }
  60.         else if (hex == 'D')
  61.         {
  62.             element = "13";
  63.            
  64.         }
  65.         else if (hex == 'E')
  66.         {
  67.             element = "14";
  68.            
  69.         }
  70.         else if (hex == 'F')
  71.         {
  72.             element = "15";
  73.            
  74.         }
  75.         return element;
  76.        
  77.     }
  78. }
Advertisement
Add Comment
Please, Sign In to add comment