Advertisement
zlatkov

FromAnyToAnyNumeralSystem

Jan 15th, 2013
46
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.83 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6.  
  7. namespace FromAnyToAnyNumeralSystem
  8. {
  9.     class FromAnyToAnyNumeralSystem
  10.     {
  11.         static int GetInt(char ch)
  12.         {
  13.             if (ch >= 'A' && ch <= 'F')
  14.             {
  15.                 return ch - 'A' + 10;
  16.             }
  17.             else
  18.             {
  19.                 return ch - '0';
  20.             }
  21.         }
  22.  
  23.         static string ConvertToDecimal(string number, int numberBase)
  24.         {
  25.             int result = 0;
  26.             int pow = 1;
  27.             for (int i = number.Length - 1; i >= 0;  --i)
  28.             {
  29.                 result += GetInt(number[i]) * pow;
  30.                 pow *= numberBase;
  31.             }
  32.  
  33.             return result.ToString();
  34.         }
  35.  
  36.         static string ConvertFromDecimal(string number, int toBase)
  37.         {
  38.             int numberInt = int.Parse(number);
  39.             string result = "";
  40.  
  41.             while (numberInt > 0)
  42.             {
  43.                 result = (numberInt % toBase) + result;
  44.                 numberInt /= toBase;
  45.             }
  46.  
  47.             return result;
  48.         }
  49.  
  50.         static void Main(string[] args)
  51.         {
  52.             Console.Write("Enter the base in which the number is represented: ");
  53.             int fromNumeralSystem = int.Parse(Console.ReadLine());
  54.  
  55.             Console.Write("Enter the base in which you want to convert the numer: ");
  56.             int toNumeralSystem = int.Parse(Console.ReadLine());
  57.  
  58.             Console.Write("Enter the number: ");
  59.             string number = Console.ReadLine();
  60.  
  61.             string decimalNumber = ConvertToDecimal(number, fromNumeralSystem);
  62.             string result = ConvertFromDecimal(decimalNumber, toNumeralSystem);
  63.  
  64.             Console.WriteLine(result);
  65.         }
  66.     }
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement