sashomaga

Convert hex to decimal

Jan 18th, 2013
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.80 KB | None | 0 0
  1. using System;
  2. //Write a program to convert hexadecimal numbers to their decimal representation
  3. class Program
  4. {
  5.     static void Main()
  6.     {
  7.         Console.WriteLine("Enter hex number : ");
  8.         string convert = Console.ReadLine();
  9.  
  10.         convert = convert.ToLower();        
  11.         int result = 0;
  12.  
  13.         for (int i = convert.Length - 1, reverse = 0; i >= 0 ; i--,reverse ++)
  14.         {
  15.             if (convert[i] <= '9')
  16.             {
  17.                 result += (convert[i] - '0') * (int)Math.Pow(16,reverse) ;
  18.             }
  19.             else if (convert[i] <= 'f')
  20.             {
  21.                 result += (convert[i] - 'a' + 10) * (int)Math.Pow(16, reverse);
  22.             }
  23.         }
  24.         Console.WriteLine("Converted number :");      
  25.         Console.WriteLine(result);
  26.     }
  27. }
Advertisement
Add Comment
Please, Sign In to add comment